1, mounted reliance
npm install svg-sprite-loader --save-dev
2, the configuration in the config file
chainWebpack(config) { // 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() }
3, in the src / components new folder and file SvgIcon / index.vue, index.vue are as follows
The following code 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>
4, in the src new folder icons, folder icons and folder svg, The index.js file, the file contents are as follows The index.js
Wherein index.js code is as follows:
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)
5, is introduced in the main.js
import '@/icons' // icon
6, used in the project