Use svg in vue and set the size

created at 09-20-2021 views: 6

1 Installation dependencies

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

2. Create a new svg resource folder

  • src/assets/svg

Put the svg resource into this directory, and then the path will be in the configuration file

svg resource folder

3. configuration vue.config.js

vue-cli 3.x and above

const path = require('path')
module.exports = {
   chainWebpack: config => {
     // svg rule loader
     const svgRule = config.module.rule('svg') // find svg-loader
     svgRule.uses.clear() // Clear the existing loader, if not, it will be added after this loader
     svgRule.exclude.add(/node_modules/) // Regular matching excludes the node_modules directory
     svgRule // Add new loader processing for svg
       .test(/\.svg$/)
       .use('svg-sprite-loader')
       .loader('svg-sprite-loader')
       .options({
         symbolId:'icon-[name]',
       })
     // Modify images loader to add svg processing
     const imagesRule = config.module.rule('images')
     imagesRule.exclude.add(path.resolve(__dirname,'src/assets/svg')) //Pay attention to this path, which is the path of the svg resource file
     config.module
       .rule('images')
       .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
   }
}

4. Create the component SvgIcon.vue

  • src/compoments/SvgIcon.vue
1 <template>
 2   <svg :class="svgClass" aria-hidden="true">
 3     <use :xlink:href="iconName"></use>
 4   </svg>
 5 </template>
 6 
 7 <script>
 8 export default {
 9   name: 'svg-icon',
10   props: {
11     iconClass: {
12       type: String,
13       required: true
14     },
15     className: {
16       type: String
17     }
18   },
19   computed: {
20     iconName () {
21       return `#icon-${this.iconClass}`
22     },
23     svgClass () {
24       if (this.className) {
25         return 'svg-icon ' + this.className
26       } else {
27         return 'svg-icon'
28       }
29     }
30   }
31 }
32 </script>
33 
34 <style scoped>
39 </style>

5. Component registration (global)

  • src/utils/iconsSvg.js
import Vue from'vue'
import SvgIcon from'@/components/SvgIcon' //Introduce the component of the fourth step

// Globally register components
Vue.component('svg-icon', SvgIcon)
// Define a function to load the directory
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('@/assets/svg', false, /\.svg$/) //is the path of the svg resource file
// Load all svg files in the directory 10 requireAll(req)

6. Introduce the component main.js

import './utils/iconsSvg'

7. Use svg components

iconClass: the file name of the svg file
className: svg icon style class name

<template>
   <div>
     <p>Your avatar</p>
     <svg-icon iconClass="boy" className="boy"></svg-icon>
   </div>
</template>

<style scoped>
.boy {
   width: 200px;
   height: 200px;
}
</style>
created at:09-20-2021
edited at: 09-20-2021: