vue 自定义svg组件加载svg图标
文章目录
安装
npm install svg-sprite-loader --save-dev
自定义组件src\components\svgIcon\index.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>
新建目录src\assets\icons
,用来存放svg图标文件
如:
src\assets\icons\api.svg
src\assets\icons\captcha.svg
src\assets\icons\close.svg
新建src\assets\icons\index.js
import Vue from 'vue'
import SvgIcon from '@/components/svgIcon'// svg组件
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
main.js进行引入
import './assets/icons/index.js'
配置vue.config.js
const path = require('path')
module.exports = {
chainWebpack: config => {
const svgRule = config.module.rule('svg')
svgRule.uses.clear()
svgRule
.test(/\.svg$/)
.include.add(path.resolve(__dirname, './src/assets/icons')).end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
const fileRule = config.module.rule('file')
fileRule.uses.clear()
fileRule
.test(/\.svg$/)
.exclude.add(path.resolve(__dirname, './src/assets/icons'))
.end()
.use('file-loader')
.loader('file-loader')
}
}
使用组件
<template>
<div>
<!-- icon-class的值就是svg的文件名 -->
<svg-icon icon-class="captcha"></svg-icon>
</div>
</template>
<script>
import svgIcon from './components/svgIcon/index.vue'
export default {
components: {
svgIcon,
}
};
</script>