Vue uses svg globally

1. Installation dependencies

 npm install svg-sprite-loader

2. Configuration options Configure the following code in
the chainWebpack of vue.config.js Explanation: config.module.rule is a method used to obtain the rules of an object. .exclude.add (file a) is to add file a to the disabled group, that is, to disable file a. .test(/.svg$/) is a file matching the end of .svg

config.module
			.rule('svg')
			.exclude.add(resolve('src/icons')) //对应下面配置svg的路径
			.end();

		config.module
			.rule('icons')
			.test(/\.svg$/)
			.include.add(resolve('src/icons')) //对应下面配置svg的路径
			.end()
			.use('svg-sprite-loader')
			.loader('svg-sprite-loader')
			.options({
    
    
				symbolId: 'icon-[name]'
			});

3. Define components
By encapsulating svg into components, we can call svg images in the form of components. Write components under components.
![Insert picture description here](https://img-blog.csdnimg.cn/32965f01cca749f19275783e8959b175.png

componnets/svgIcon/index.vue:

<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: 10em;
    height: 10em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
</style>

4. Store images and register globally
Create a file directory and place svg images
I put svg images in the src/icons/svg folder, and then register svgIcon as a global component
insert image description here
src/icons/index.js:

import Vue from 'vue'
import SvgIcon from '@/components/svgIcon/index'// 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)

5. Global import
Import the registration file in mian.js

import './icons'

6. Use
For example, there is a picture rain.svg, the path is icons/svg/rain.svg, and then it can be called directly by the name. Here className is a custom style


//<svg-icon icon-class="图片名" className="样式类"></svg-icon>
<svg-icon icon-class="rain" className="iconBig"></svg-icon>

Guess you like

Origin blog.csdn.net/qq_43840793/article/details/130152299
SVG