一. 下载插件
npm i svg-sprite-loader@4.1.3
二. 配置 vue.config.js
顶部加
const path = require('path')
function resolve (dir) {
return path.join(__dirname, dir)
}
module.exports 里加
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()
}
三. 创建目录
(1) src/icons
将资源文件放入src下
链接:https://pan.baidu.com/s/13jN1bBp6985lH5-j33Fshg?pwd=jv3c
提取码:jv3c
--来自百度网盘超级会员V6的分享
(2) 创建组件 componets/SvgIcon/index.vue
<template>
<div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
<svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
import { isExternal } from '@/utils/validate'
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
isExternal () {
return isExternal(this.iconClass)
},
iconName () {
return `#icon-${this.iconClass}`
},
svgClass () {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
},
styleExternalIcon () {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover!important;
display: inline-block;
}
</style>
(3)创建工具层文件 utils/validate.js
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal (path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
四. 在main.js中引入
import '@/icons'
五. 正式使用
<svg-icon icon-class="SVG文件名"/>
↓↓实际效果↓↓↓