vue cli3项目中使用svg图标

1. 安装 webpack 插件 svg-sprite-loader

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

2. 在 vus.config.js 中添加以下内容

const path = require(path)
module.exports = {
          
   
  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)
  }
}

3. src/components 创建 SvgIcon 组件

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>
export default {
           
    
  name: svg-icon,
  props: {
           
    
    iconClass: {
           
    
      type: String,
      required: true
    },
    className: {
           
    
      type: String
    }
  },
  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: 1.2em;
  height: 1.2em;
  vertical-align: -0.18em;
  fill: currentColor;
  overflow: hidden;
}
</style>

4. 在src目录下创建icons文件夹

文件夹下面有svg文件夹和index.js文件

index.js文件作用是使用webpack 的 require.context 自动引入 @/src/icons 下面所有的图标,svg文件夹用于存放svg图标文件 index.js文件:

import Vue from vue
import SvgIcon from @/components/SvgIcon// svg组件

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

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

5. main.js 中引入组件

import ./icons // icon

6. 组件引用

<svg-icon icon-class="xxx" />
//xxx为svg图标文件名
经验分享 程序员 微信小程序 职场和发展