安装 svg-sprite-loader
1
| npm i -S svg-sprite-loader
|
更改 build/webpack.base.conf.js 配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| { test: /\.svg$/, loader: 'svg-sprite-loader', include: [path.resolve(__dirname, '../src/images/icons')], options: { } }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url', exclude: [resolve('src/icons')], query: { limit: 10000, name: utils.assetsPath('img/[name].[ext]') } }
|
下载 svg 文件并放入 src/icons/svg/目录下
推荐阿里图标库 https://www.iconfont.cn/
封装组件 components/common/SvgIcon.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
| <svg :class="svgClass" aria-hidden="true"> <use :xlink:href="iconName"></use> </svg>
<script> export default { name: "svg-icon", 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: 1.5em; height: 1.5em; vertical-align: middle; fill: currentColor; overflow: hidden; } </style>
|
新建 src/icons/index.js 文件
1 2 3 4 5 6 7
| import Vue from "vue"; import SvgIcon from "../../components/common/SvgIcon";
Vue.component("svg-icon", SvgIcon); const requireAll = requireContext => requireContext.keys().map(requireContext); const req = require.context("./svg", false, /\.svg$/); requireAll(req);
|
main.js 中引入
使用
1
| <svg-icon icon-class="search"></svg-icon>
|