vue版本2.6.14
目录如下
package.json
// devDependencies中安装开发依赖
"svg-sprite-loader": "^6.0.11",
vue.config.js
const { defineConfig } = require('@vue/cli-service')
const path = require('path');
function resolve (dir) {
return path.join(__dirname, dir)
}
module.exports = defineConfig({
devServer: {
open: true,
host: 'localhost',
port: 8080
},
transpileDependencies: true,
lintOnSave: false,
chainWebpack: config => {
config.module
.rule('svg')
.exclude.add(resolve('src/assets/svg'))
.end();
config.module
.rule('svgs-loader')
.test(/\.svg$/)
.include.add(resolve('src/assets/svg'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end();
}
})
SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
// svg图标名称
iconClass: {
default: ''
},
// 自定义样式
className: {
type: String,
default: ''
},
},
computed: {
iconName() {
return `#icon-${this.iconClass}`;
},
svgClass() {
return [
'svg-icon',
this.className ? this.className:''
]
}
}
};
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
svg-icon/index.js
import SvgIcon from './SvgIcon.vue'
export default (Vue) => {
// 全局注册
Vue.component('svg-icon', SvgIcon);
// 导入所有svg文件
const requireAll = requireContext => requireContext.keys().map(requireContext);
const req = require.context('@/assets/svg', false, /\.svg$/);
requireAll(req);
}
index
import SvgIcon from "./svg-icon";
export default (Vue) => {
Vue.use(SvgIcon);
}
main.js
// 增加
import PublicComponent from '@/components'
Vue.use(PublicComponent);
使用组件
<svg-icon icon-class="add" class="svg-color"/>
<style scoped>
.svg-color {
color: red;
}
</style>