1.安装 svg-sprite-loader
npm i svg-sprite-loader -D //npm
yarn add svg-sprite-loader //yarn
2.components下面创建SvgIcon文件然后下面再建一个index.vue
components/SvgIcon/index.vue
index.vue
<template>
<svg class="svg-icon"
aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
},
computed: {
iconName() {
return `#icon-${this.iconClass}`
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1.3em;
height: 1.3em;
vertical-align: -0.15em;
/* fill: currentColor; */
overflow: hidden;
}
</style>
3.src下面创建 icons文件下面有svg图标文件夹和index.js
index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon/index.vue'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
4.根目录新建 vue.config.js 配置 svg-sprite-loader
src/icons路径是需要跟上面步骤3 对应的上的 如果你的icon文件建立在assets文件下面那就是assets/icons
'use strict'
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')) //src/icons路径是需要跟上面步骤3 对应的上的
.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()
}
}
5.main.js引入
import "@/icons";
6.页面上使用(icon-class:是你下载的svg 图标的名称)
<svg-icon icon-class="kefu"/>