How to use THE SVG-Icon component in a new project

1. Install dependency packages

 npm i svg-sprite-loader@4.13.
Copy the code

2. Configure the vue. Config. Js

const path = require('path')
function resolve (dir) {
  return path.join(__dirname, dir)
}
Copy the code

Add a configuration {}

module.exports ={
  // omit other...
  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()
  }
Copy the code

3. Create a file

(1) src/icons

SRC/ICONS - / SVG # Save ICONS - /index.js # Register global components -` `(2) Component` `js
componets/SvgIcon/index.vue
Copy the code

Attached code:

<template>
  <div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
  <svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
import { isExternal } from '@/utils/validate'

export default {
  name: 'SvgIcon'.props: {
    iconClass: {
      type: String.required: true
    },
    className: {
      type: String.default: ' '}},computed: {
    isExternal() {
      return isExternal(this.iconClass)
    },
    iconName() {
      return `#icon-The ${this.iconClass}`
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'}},styleExternalIcon() {
      return {
        mask: `url(The ${this.iconClass}) no-repeat 50% 50%`.'-webkit-mask': `url(The ${this.iconClass}) no-repeat 50% 50%`}}}}</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15 em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover! important;
  display: inline-block;
}
</style>
Copy the code

(3) validate. Js

utils/validate.js
Copy the code

(4) introduced in main.js

import '@/icons'
Copy the code

(5) Use the format< svG-icon icon-class=" filename "/>. The file name here is insrc/icons/svgFile name under

The file name must be in your project to display the image file name

It can’t be displayed without this file