Step 1: Install the svg-sprite-loader plugin
npm install -S svg-sprite-loader
Step 2: Encapsulate the svg component
<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: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
Step 3: Put the required svg icons into the directory
Step 4: Configure
It can be configured in webpack.config.js or vue.config.js, the code is as follows
module.exports = {
chainWebpack (config) {
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
}
Step 5: Global Registration
Create index.js file in the icons directory
The content in index.js is as follows
import Vue from 'vue'
import SvgIcon from '../../components/svgIcon'// 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)
Step 6: Import globally in main.js
import './assets/icons/index';
Step Seven: Use
code show as below:
<!-- icon-class的值对应的是目录中svg的名子 -->
<p><svg-icon icon-class="user" /></p>
<p><svg-icon icon-class="advert" color='#27ac3d'/></p>
<p><svg-icon icon-class="brand" color='red'/></p>
The effect is as follows
Note: If the icon is not displayed, please re-run the project.
If it is not displayed after running, please check whether the imported path in the corresponding place is correct, especially the path in vue.config.js.