Install the svg plugin
npm i [email protected]
Create svg component
Create the SvgIcon folder in the components folder under src, and create the index.vue file under the SvgIcon folder
The code of index.vue is as follows
<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'
}
},
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>
Create an icons folder under src Create an svg folder under icons (svg images are stored in svg) and index.js file
Globally register the SvgIcon component written above in 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)
Configure in vue.config.js (you need to restart the project after modification)
const { defineConfig } = require("@vue/cli-service");
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack(config) {
config.module
.rule('svg')
.exclude.add(resolve('src/icons/svg'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons/svg'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
},
});
Import the icons file into main.js
import './icons'
Use the svg-icon component
Use svg-icon directly in the vue file to write the corresponding svg name without registering the icon-class on the page again
If you need to add a class name, use class-name to pass
<svg-icon icon-class="reset" class-name="reset"></svg-icon>