1. Install SVG – Sprite – loader

npm install -D svg-sprite-loader

2. Configure the vue. Config. Js

'use strict'
const path = require('path')
function resolve(dir) {
    return path.join(__dirname, dir)
}

module.exports = {
    chainWebpack(config){
      const svgRule = config.module.rule('svg') / / find the SVG - loader
      svgRule.uses.clear() // Clear the existing loader
      svgRule.exclude.add(/node_modules/) // Regular matches exclude the node_modules directory
      svgRule // Add a new loader handle for SVG
        .test(/\.svg$/)
        .use('svg-sprite-loader')
        .loader('svg-sprite-loader')
        .options({
          symbolId: 'icon-[name]'
        })
        
      const imagesRule = config.module.rule('images')
      imagesRule.exclude.add(resolve('src/icons'))
      config.module
        .rule('images')
        .test(/\.(png|jpe? g|gif|svg)(\? . *)? $/)}}Copy the code

3. Create SvgIcon in Components

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>
export default {
  name: 'svg-icon'.props: {
    iconClass: {
      type: String.required: true
    },
    className: {
      type: String}},computed: {
    iconName() {
      return `#icon-The ${this.iconClass}`
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'}}}}</script>

<style scoped>
.svg-icon {
  width: 1.2 em;
  height: 1.2 em;
  vertical-align: -0.18 em;
  fill: currentColor;
  overflow: hidden;
}
</style>
Copy the code

4. Create an ICONS folder in the SRC directory, where SVG stores the images with the suffix.svg and index.js as follows:

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// Import the SVG component

Vue.component('svg-icon', SvgIcon)

const requireAll = requireContext= > requireContext.keys().map(requireContext)
const req = require.context('./svg'.false./\.svg$/)
requireAll(req)

Copy the code

5. Import from main.js

6. Use it in components