第一步 npm i -D svg-sprite-loader
第二步 webpack.base.conf.js下添加
{ test: /\.svg$/, loader: 'svg-sprite-loader', include: [resolve('src/icons')], options: { symbolId: 'icon-[name]' } }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', exclude: [resolve('src/icons')], options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } },
第三步 src目錄下新建文件夾icons,其中svg文件夾下放svg類型的圖片,index.js代碼如下
import Vue from 'vue' import SvgIcon from '@/components/SvgIcon'// svg component Vue.component('svg-icon', SvgIcon) const req = require.context('./svg', false, /\.svg$/) const requireAll = requireContext => requireContext.keys().map(requireContext) requireAll(req)第
第四步 在components下新建文件夾SvgIcon,index.vue代碼如下
<!-- 組件說明 --> <template> <svg class="svg-icon"> <use :xlink:href="iconName" /> </svg> </template> <script> //import x from '' export default { name: "SvgIcon", props: { iconClass: { type: String, required: true }, }, computed: { iconName() { return `#icon-${this.iconClass}`; }, } }; </script> <style scoped> .svg-icon { width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden; } </style>
第五步 在main.js中引入 import './icons'
第六步 如何使用 <svg-icon icon-class="user" />