安装 svg-sprite-loader
svg-sprite-loader 是用于创建SVG精灵图的插件,通过该插件可以将导入的SVG文件自动生成为symbol标签并插入进html中
yarn add svg-sprite-loader -D
配置加载插件
在 vue.config.js
中添加插件。
1 | const path = require("path")
|
2 |
|
3 | function resolve(dir) {
|
4 | return path.join(__dirname, dir);
|
5 | }
|
6 |
|
7 | module.exports = {
|
8 | css: {
|
9 | loaderOptions: {
|
10 | less: {
|
11 | javascriptEnabled: true,
|
12 | },
|
13 | },
|
14 | },
|
15 | chainWebpack(config){
|
16 |
|
17 | config.module.rule("svg").uses.clear();
|
18 |
|
19 | config.module
|
20 |
|
21 | .rule("svg-sprite-loader")
|
22 | .test(/.svg$/)
|
23 | .exclude.add(/node_modules/)
|
24 | .end()
|
25 |
|
26 | .test(/\.svg$/)
|
27 | .include.add(path.resolve(__dirname, './src/icons/svg'))
|
28 | .end()
|
29 | .use("svg-sprite-loader")
|
30 | .loader("svg-sprite-loader")
|
31 |
|
32 | .options({
|
33 | symbolId: "[name]"
|
34 | });
|
35 | }
|
36 | }
|
导入 SVG
创建文件目录和文件
src/icons
src/icons/index.js
svg 文件操作
/src/icon/svg
svg 文件存放
1 |
|
2 | * 加载 svg
|
3 | */
|
4 | function loadSvg() {
|
5 | const requireAll = (requireContext) => requireContext.keys().map(requireContext);
|
6 | const req = require.context("@/icons/svg/", false, /\.svg$/);
|
7 | requireAll(req);
|
8 | }
|
icon-svg 组件
1 | <template>
|
2 | <svg class="icon-svg" aria-hidden="true">
|
3 | <use :xlink:href="iconName"></use>
|
4 | </svg>
|
5 | </template>
|
6 | <script>
|
7 | export default {
|
8 | name: "icon-svg",
|
9 | inheritAttrs: true,
|
10 | props: {
|
11 | name: {
|
12 | type: String
|
13 | },
|
14 | },
|
15 | computed: {
|
16 | iconName() {
|
17 | return `#icon-${this.name}`;
|
18 | },
|
19 | },
|
20 | };
|
21 | </script>
|
22 | <style>
|
23 | .icon-svg {
|
24 | width: 1em;
|
25 | height: 1em;
|
26 | vertical-align: -0.15em;
|
27 | fill: currentColor;
|
28 | overflow: hidden;
|
29 | }
|
30 | </style>
|
使用
1 | // 基本使用
|
2 | <icon-svg name="setting" />
|
3 |
|
4 | // 通过 style 控制大小和颜色
|
5 | <icon-svg name="setting" style="fontSize:18px;color:#1abc9c;"/>
|
6 |
|
7 | // 通过 class 控制大小和颜色
|
8 | <icon-svg name="setting" class="setting"/>
|
如果修改颜色无效的话,打开文件将里面的 fill 删除。