vue项目实现svg图标组件

1.首先在项目中引入 svg-sprite-loader (一个用于创建 svg 雪碧图的 Webpack 加载器)

npm install svg-sprite-loader -D

2.创建svg组件

<template>    
    <svg :class="svgClass" aria-hidden="true">
        <use  :xlink:href="iconName" />
    </svg>
</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{
     width: 1em;
     height: 1em;
     vertical-align: -0.15em;
     fill: currentColor;
     overflow: hidden; 
  }
</style>

3.在项目中创建icon文件夹,一般放在 src/assets下

4.创建index.js文件,将引入所有的svg图标,将svg组件挂在到全局

import Vue from "vue"   
import svgIcon from "../../components/common/SvgIcon.vue"
Vue.component('svg-icon',svgIcon)  //挂载全局组件
//下面这个是导入svgIcon/svg下的所有svg文件    
 const requireAll = requireContext => requireContext.keys().map(requireContext)
 const req = require.context('./icons', true, /.svg$/)   
/*    
  第一个参数是:'./svg' => 需要检索的目录,  
  第二个参数是:false => 是否检索子目录,
  第三个参数是: /.svg$/ => 匹配文件的正则
*/    
requireAll(req);

 5.在mian.js文件中引入

6.修改配置文件 vue.config.js(根目录没有这个文件,就新创建一下),修改webpack配置

const path = require ('path');

function resolve (resolvePath) {
    return path.join (__dirname, resolvePath);
  }
  
module.exports = {
   //在配置项中添加如下内容
    chainWebpack: config => {
        config.module.rule ('svg').exclude.add (resolve ('./src/assets/icon/icons'));
        const svgRule = config.module.rule("icons").test (/\.svg$/).include.add (resolve ('./src/assets/icon/icons')).end () ;   
           svgRule.uses.clear();
           svgRule
           .use("svg-sprite-loader")
           .loader("svg-sprite-loader")
           .options({
              symbolId: "icon-[name]"
            });
        },
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值