安装依赖
npm i svg-sprite-loader -D下载svg图标
存入src/icons/svg
新增并编辑配置文件
vue.config.js
const path = require('path')
//resolve定义一个绝对路径获取函数
function resolve(dir){
return path.join(__dirname, dir)
}
chainWebpack(config){
//配置svg规则排除icons目录中svg文件处理
config.module .rule("svg") .exclude.add(resolve("src/icons")) .end(); // 新增icons规则,设置svg-sprite-loader处理icons目录中的svg 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(); }图标自动导入
// icons/index.js const req = require.context('./svg', false, /\.svg$/) req.keys().map(req); 创建SvgIcon组件,./components/SvgIcon.vue
<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>注册
//main.js
import './icons'
import SvgIcon from '@/components/SvgIcon.vue' Vue.component('svg-icon', SvgIcon) //main.js
import './icons'
import SvgIcon from '@/components/SvgIcon.vue'
Vue.component('svg-icon, SvgIcon)使用
<svg-icon icon-class="imageName"></svg-icon>