一,安装svg-sprite-loader
liuhongdi@lhdpc:/data/vue/svgdemo$ npm install svg-sprite-loader --save-dev added 47 packages in 11s 14 packages are looking for funding run `npm fund` for details
说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,创建访问svg的类
1,创建svgIcon目录,并在其下创建svg目录: 如图:
2,user.svg
<svg width="130" height="130" xmlns="http://www.w3.org/2000/svg"><path d="M63.444 64.996c20.633 0 37.359-14.308 37.359-31.953 0-17.649-16.726-31.952-37.359-31.952-20.631 0-37.36 14.303-37.358 31.952 0 17.645 16.727 31.953 37.359 31.953zM80.57 75.65H49.434c-26.652 0-48.26 18.477-48.26 41.27v2.664c0 9.316 21.608 9.325 48.26 9.325H80.57c26.649 0 48.256-.344 48.256-9.325v-2.663c0-22.794-21.605-41.271-48.256-41.271z" stroke="#979797"/></svg>
3, svgIcon/index.js
//导入svgIcon/svg下的所有svg文件 const requireAll = requireContext => requireContext.keys().map(requireContext); /* 第一个参数是:'./svg' => 需要检索的目录, 第二个参数是:false => 是否检索子目录, 第三个参数是: /.svg$/ => 匹配文件的正则 */ const req = require.context("./svg", false, /.svg$/); requireAll(req);
4, svgIcon/index.vue
<template> <svg :class="svgClass" v-bind="$attrs" :style="{color: color}"> <use :xlink:href="iconName"/> </svg> </template> <script setup> import { defineProps, computed } from "vue"; const props = defineProps({ name: { type: String, required: true }, color: { type: String, default: '' } }) const iconName = computed(()=>`#icon-${props.name}`); const svgClass = computed(()=> { console.log(props.name, 'props.name'); if (props.name) { return `svg-icon icon-${props.name}` } return 'svg-icon' }); </script> <style scoped> .svg-icon { width: 1em; height: 1em; fill: currentColor; vertical-align: middle; } </style>
5,main.js
import { createApp } from 'vue' import App from './App.vue' import "@/svgIcon/index" import svgIcon from "@/svgIcon/index.vue"; createApp(App).component("svg-icon", svgIcon).mount('#app')
三,配置vue.config.js使支持访问svg
vue.config.js
module.exports = { chainWebpack: config => { const svgRule = config.module.rule("svg"); svgRule.uses.clear(); svgRule .use("svg-sprite-loader") .loader("svg-sprite-loader") .options({ symbolId: "icon-[name]" }); } }
四,测试效果:
五,查看版本
1,查看loader的版本
liuhongdi@lhdpc:/data/vue/svgdemo$ npm list svg-sprite-loader svgdemo@0.1.0 /data/vue/svgdemo └── svg-sprite-loader@6.0.9
2,查看vue的版本:
liuhongdi@lhdpc:/data/vue/svgdemo$ npm list vue svgdemo@0.1.0 /data/vue/svgdemo ├─┬ @vue/cli-plugin-babel@4.5.14 │ └─┬ @vue/babel-preset-app@4.5.14 │ └── vue@3.2.20 deduped └── vue@3.2.20