一、安裝依賴vue
npm install svg-sprite-loader --save-dev
二、在config文件中配置npm
chainWebpack(config) { // set svg-sprite-loader config.module .rule('svg') .exclude.add(resolve('src/icons')) .end() config.module .rule('icons') .test(/\.svg$/) .include.add(resolve('src/icons')) .end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) .end() }
三、在src/components下新建文件夾及文件SvgIcon/index.vue,index.vue中內容以下svg
index.vue中的代碼以下ui
<template> <svg :class="svgClass" aria-hidden="true" v-on="$listeners"> <use :xlink:href="iconName"/> </svg> </template> <script> export default { name: 'SvgIcon', props: { iconClass: { type: String, required: true }, className: { type: String, default: '' } }, 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>
四、在src下新建icons文件夾,及icons文件夾下svg文件夾、index.js文件, index.js文件內容以下this
其中index.js代碼以下:spa
import Vue from 'vue' import SvgIcon from '@/components/SvgIcon'// svg組件 // register globally Vue.component('svg-icon', SvgIcon) const req = require.context('./svg', false, /\.svg$/) const requireAll = requireContext => requireContext.keys().map(requireContext) requireAll(req)
五、在main.js中引入code
import '@/icons' // icon
六、在項目中使用component
在 阿里icon適量圖庫隨便下載個svg格式的圖,blog
在svg文件夾下,建立一個test.svg文件,將複製下來的svg代碼貼進去ip
在項目中使用
<svg-icon icon-class="test"></svg-icon>
效果: