vue(vue2)使用svg格式图标

        先安装插件
        

  1. 配置svg文件夹,新建icons文件,svg文件夹放svg后缀文件

    index.js文件中的配置

    import Vue from "vue"
    import svgIcon from "@/common/iconSvg/index.vue"
     
    Vue.component('svg-icon',svgIcon)  //挂载全局组件
     
    //下面这个是导入svgIcon/svg下的所有svg文件
    const requireAll = requireContext => requireContext.keys().map(requireContext)
    const req = require.context('./svg', false, /.svg$/) 
      /*
       第一个参数是:'./svg' => 需要检索的目录,
       第二个参数是:false => 是否检索子目录,
       第三个参数是: /.svg$/ => 匹配文件的正则
      */
      requireAll(req);
  2. common文件夹下建vue文件(该文件路径根据自己项目文件夹,我是放到了common)
    <template>
      <div>
        <svg :class="svgClass" aria-hidden="true">
          <use :xlink:href="iconName" />
      </svg>
      </div>
    </template>
    <script>
    export default {
     name:'svgIcon',
     props:{
        data_iconName:{
            type:String,
            required:true
        },
        className:{
            type:String,
            default:''
        }
     },
     computed:{
         svgClass(){   //svg 的class
             if(this.className){
                 return `svg-icon ${this.className}`;
             }else{
                 return 'svg-icon'
             }
         },
         iconName(){  //svg xlink-href 指向的文件名
             return `#icon-${this.data_iconName}`;
         }
     }
    }
    </script>
     
    <style scoped>
    .svg-icon{
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
    }
    </style>
  3. main.js文件中引入

     

  4. vue.config.js中配置

    const path = require('path')
    chainWebpack: config => {
        config.plugins.delete("prefetch")
        config.plugins.delete("preload")
        config.module
          .rule('svg')
          .exclude.add(path.join(__dirname, 'src/assets/icons'))
          .end()
        config.module
          .rule('icons')// 定义一个名叫 icons 的规则
          .test(/.svg$/)// 设置 icons 的匹配正则
          .include.add(path.join(__dirname, 'src/assets/icons'))// 设置当前规则的作用目录,只在当前目录下才执行当前规则
          .end()
          .use('svg-sprite')// 指定一个名叫 svg-sprite 的 loader 配置
          .loader('svg-sprite-loader')// 该配置使用 svg-sprite-loader 作为处理 loader
          .options({// 该 svg-sprite-loader 的配置
            symbolId: 'icon-[name]'
          })
          .end()
      },
  5. 最后使用

    <svg-icon data_iconName="changtinglogo" className="loginlogoSvg" />