vue中如何使用svg
我使用的是svg-sprite-loader插件
在public同级目录下新建icons文件夹,在分别创建svg文件夹和index.js文件
在封装一个SvgIcon组件
在vue.config.js配置
chainWebpack: config => {
isProd && config.plugin('optimize-css').tap(([options]) => {
if (options && options.cssnanoOptions) {
options.cssnanoOptions.preset[1].svgo = false;
}
return [options];
})
// 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()
},
使用时,通过className定义类名
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,
require: 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: 1.54666rem;
height: 1.54666rem;
}
.guide {
width: 1rem;
height: 1rem;
}
.laye {
width: 0.58667rem;
height: 0.58667rem;
}
.send {
width: 0.4rem;
height: 0.42666rem;
}
.records {
width: 0.45333rem;
height: 0.45rem;
}
.shared {
width: 0.42667rem;
height: 0.42666rem;
}
.voice {
width: 0.48rem;
height: 0.53333rem;
}
.exchange {
width: 0.42667rem;
height: 0.48rem;
}
.icon-2d, .icon-3d, .retroaction {
margin-top: -0.2rem;
}
</style>
在src/icons/index.js
import Vue from 'vue';
import SvgIcon from '@/components/SvgIcon';
// 注册全局组件
Vue.component('svg-icon', SvgIcon);
const req = require.context('./svg', false, /\.svg$/);
const requireAll = requireContext => requireContext.keys().map(requireContext);
requireAll(req);
最后在main.js引入