通过symbol方式使用图标
前端构件中常常会用到各种小图标,使用图标的方式有很多,这里选择了symbol方式导入svg-icon。
原因是:这种方式设置好模板和相关配置后,想使用新的图标只需将icon的svg文件放入指定文件夹,通过文件名便可使用图标,更新方便。
参考网站
一个好用的svg加载器svg-sprite-loader
手摸手,带你优雅的使用 icon
iconfont官网
安装svg-sprite-loader
1
| npm i svg-sprite-loader -D
|
配置vue.config.js
1 2 3 4
| const path = require("path"); function resolve(dir) { return path.join(__dirname, dir); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| chainWebpack: (config) => { config.module .rule("svgIcon") .test(/\.svg$/) .include.add(resolve("src/icons")) .end() .use("svg-sprite-loader") .loader("svg-sprite-loader") .tap((options) => { options = { symbolId: "icon-[name]", }; return options; });
config.module.rule("svg").exclude.add(resolve("src/icons")).end(); },
|
在components目录下创建svgIcon/index.vue组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <template> <svg :class="svgClass" aria-hidden="true"> <use :xlink:href="iconName" /> </svg> </template>
<script> export default { name: "SvgIcon", props: { iconClass: { type: String, required: true, }, className: { type: String, }, }, computed: { iconName() { return `#icon-${this.iconClass}`; }, svgClass() { if (this.className) { return "svg-icon " + this.className; } else { return "svg-icon"; } }, }, }; </script>
<style scoped> .svg-icon { width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden; } </style>
|
全局注册svg 组件
在src/icons目录下,分别创建svg目录和index.js文件。svg目录存放.svg格式的文件。
1 2 3 4 5 6 7 8
| import Vue from "vue"; import SvgIcon from "../components/svgIcon/index";
Vue.component("svg-icon", SvgIcon);
const requireAll = (r) => r.keys().map(r);
requireAll(require.context("./svg", false, /\.svg$/));
|
在 main.js 项目入口文件中导入 icons 文件
使用
1 2 3
| //icon-class:svg图片的文件名,例如下方代码使用了 QQ.svg 文件 //class-name:svg图片的样式类名,可用来自定义样式 <svg-icon icon-class="QQ" class-name="icon" />
|
其他问题
使用vscode运行vue项目,正在运行的项目改动并保存时,项目会快速更新。使用上述svg icon时,热更新失效,重新npm run serve
即可。
也有其他解决方案,参见【疑难杂症】vue-cli热更新失效