Add svg images and use Ali vector image library for projects of Vue3.0 and above

1. Install the plugin

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

Two: configuration, add a loader that handles svg in Vue.config.js

//3.0版本
  chainWebpack: config => {
    const svgRule = config.module.rule('svg')
    // 清除已有的所有 loader。
    // 如果你不这样做,接下来的 loader 会附加在该规则现有的 loader 之后。
    svgRule.uses.clear()
    svgRule
        .test(/\.svg$/)
        .include.add(path.resolve(__dirname, './src/icons'))
        .end()
        .use('svg-sprite-loader')
        .loader('svg-sprite-loader')
        .options({
          symbolId: 'icon-[name]'
        })
    const fileRule = config.module.rule('file')
    fileRule.uses.clear()
    fileRule
        .test(/\.svg$/)
        .exclude.add(path.resolve(__dirname, './src/icons'))
        .end()
        .use('file-loader')
        .loader('file-loader')
  }

Third, create the icons folder in the root directory to put all the svg files, or you can go directly to the github official website to download the icons file address and copy it directly

Insert picture description here
Insert picture description here

index.js code

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component

// register globally
Vue.component('svg-icon', SvgIcon)

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

Create a new folder and file SvgIcon/index.vue under src/components

Insert picture description here

index.vue code: .svg-icon: customizable size

<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>

Fourth, introduce and register in main.js

Insert picture description here

Five, use

Insert picture description here
Insert picture description here

<svg-icon icon-class="svg的文件名" class-name="card-panel-icon" />

Go to Ali Vector Library to download the icon you need, add it to the svg directory of icons, and customize the file name and use, address: Alibaba Vector Icon Library

Insert picture description here

Learn more about the public account: the evolution of programmers

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44758515/article/details/106884058