SoFunction
Updated on 2025-04-05

Configuration method for using SVG-ICON in Vue

Use svg-icon in Vue, you can configure it as follows.

1. Created in the src/components/SvgIcon directory, the code is as follows:

<template>
  <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName" rel="external nofollow"  />
  </svg>
</template>
<script>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    }
  },
  computed: {
    iconName () {
      return `#icon-${}`
    },
    svgClass () {
      if () {
        return 'svg-icon ' + 
      } else {
        return 'svg-icon'
      }
    }
  }
}
</script>
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

2. Created under src/assets/icons/, the code is as follows:

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component// register globally
('svg-icon', SvgIcon)
const req = ('./svg', false, /\.svg$/)
const requireAll = requireContext =&gt; ().map(requireContext)
requireAll(req)

3. In the src/assets/icons/svg directory, place the used svg image file as shown in the picture

4. Add a reference to icons to the file, the code is as follows:

import './assets/icons'

5. Add the following code to the nodes in the build directory:

{
    test: /\.svg$/,
    loader: 'svg-sprite-loader',
    include: [resolve('src/assets/icons')],
    options: {
      symbolId: 'icon-[name]'
    }
},
{
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    exclude: [resolve('src/assets/icons')],
    options: {
      limit: 10000,
      name: ('img/[name].[hash:7].[ext]')
    }
},

6. Add the following code to the build node in the config directory:

chainWebpack(config) {
  // set svg-sprite-loader
  
  rule('svg')
    .(resolve('src/assets/icons'))
    .end()
  
    .rule('icons')
    .test(/\.svg$/)
    .(resolve('src/assets/icons'))
    .end()
    .use('svg-sprite-loader')
    .loader('svg-sprite-loader')
    .options({
      symbolId: 'icon-[name]'
    })
  .end()
}

Note: Some projects in the above step are configured using files, and it depends on the specific configuration.

7. Execute the following command to install the svg-sprite-loader plug-in

npm install svg-sprite-loader --save-dev

8. How to quote the svg icon in the code

<svg-icon icon-class="user"></svg-icon>

This is the end of this article about using SVG-ICON in Vue. For more related content on using SVG-ICON in Vue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!