usevite-plugin-svg-iconsThe plug-in

  • Install dependencies
yarn add vite-plugin-svg-icons -D
Copy the code
  • Use the plug-in in viet.config.js
import viteSvgIcons from 'vite-plugin-svg-icons'; import path from 'path'; Export default () => {return {plugins: [viteSvgIcons({// specify the ICONS folder iconDirs to cache: [path. Resolve (process. CWD (), 'SRC/ICONS')], / / perform icon name format symbolId: 'icon - [dir] - [name]',}),]}; };Copy the code
  • Introduced in main.js
import 'virtual:svg-icons-register';
Copy the code
  • Create the svgicon.vue component
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" :fill="color" />
  </svg>
</template>

<script>
import { computed } from 'vue'
export default defineComponent({
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    },
    color: {
      type: String,
      default: ''
    },
  },
  setup(props) {
    return {
      iconName: computed(() => `#icon-${props.iconClass}`),
      svgClass: computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`
        }
        return 'svg-icon'
      })
    }
  }
})
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  position: relative;
  fill: currentColor;
  vertical-align: -2px;
}
</style>
Copy the code
  • The global

Add to mian.js

import SvgIcon from '@/components/SvgIcon'
app.component('svg-icon',SvgIcon)
Copy the code
  • Use in components
import { defineComponent } from 'vue'
import SvgIcon from '@/components/SvgIcon'
export default defineComponent({
  components:{
     SvgIcon
  }
})
Copy the code