vue项目中使用 SVG 组件

使用 SVG 组件

1. 安装 svg-sprite-loader

npm i -D svg-sprite-loader

2. 新增 SvgIcon 组件

 1 <template>
 2   <svg class="svg-icon"
 3        aria-hidden="true">
 4     <use :xlink:href="iconName" />
 5   </svg>
 6 </template>
 7 
 8 <script>
 9 export default {
10   name: 'SvgIcon',
11   props: {
12     iconClass: {
13       type: String,
14       required: true
15     }
16   },
17   computed: {
18     iconName() {
19       return `#icon-${this.iconClass}`
20     }
21   }
22 }
23 </script>
24 
25 <style scoped>
26 .svg-icon {
27    1em;
28   height: 1em;
29   vertical-align: -0.15em;
30   fill: currentColor;
31   overflow: hidden;
32 }
33 </style>

3. 在 src 文件夹中创建 icons 文件夹。icons 文件夹中新增 svg 文件夹(用来存放 svg 文件)与 index.js 文件:

1 import SvgIcon from "@/components/SvgIcon";
2 import Vue from "vue";
3 
4 // 注册到全局
5 Vue.component("svg-icon", SvgIcon);
6 
7 const requireAll = requireContext => requireContext.keys().map(requireContext);
8 const req = require.context("./svg", false, /.svg$/);
9 requireAll(req);

4. 在 main.js 中导入 icons/index.js

1 import "@/icons";

5. 修改 vue.config.js

 1 const path = require("path");
 2 const resolve = dir => path.join(__dirname, dir);
 3 
 4 module.exports = {
 5   chainWebpack: config => {
 6     const svgRule = config.module.rule("svg");
 7     svgRule.uses.clear();
 8     svgRule.exclude.add(/node_modules/);
 9     svgRule.include.add(/src/icon/);
10     svgRule
11       .test(/.svg$/)
12       .use("svg-sprite-loader")
13       .loader("svg-sprite-loader")
14       .options({
15         symbolId: "icon-[name]"
16       });
17 
18     const imagesRule = config.module.rule("images");
19     imagesRule.exclude.add(resolve("src/icons"));
20     config.module.rule("images").test(/.(png|jpe?g|gif|svg)(?.*)?$/);
21   }
22 };

6. 在vue文件中使用svg,在icon-class的值修改为svg文件的名字即可

1 <svg-icon icon-class="anquan"/>
原文地址:https://www.cnblogs.com/shine-lovely/p/14043081.html