在vue3.0中优雅的适用svg-icon组件

本来一开始项目中采用的是symbol引用的方式来使用iconfont中的图标,但是这种方式存在一个弊端,每次增删改一个图标,都需要重新将项目下生成的symbol代码拷贝到自己的项目中。而且最主要的原因是菜单图标是在管理端选择的,当前项目中只通过接口返回了每一个菜单对应的icon名字,那么要如何让管理端选择的图标和当前项目中的图标保持一致呢,要想解决这个问题,只有将管理端可供菜单选择的svg图标在当前项目下再存放一份,然后自己封装一个可以灵活呈现这些svg图标的组件了。

  1. 在src目录下新建icons文件夹->svg文件夹,将所有需要的svg图标放到这个文件夹里。
  2. 在共用组件components下新建SvgIcon文件夹->index.vue。
	<template>
	 <svg :class="svgClass" aria-hidden="true">
	  <use :xlink:href="iconName"></use>
	 </svg>
	</template>
	<script>
	export default {
	 name: 'SvgIcon',
	 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>
	.svg-icon {
	   width: 1em;
	   height: 1em;
	   vertical-align: -0.15em;
	   fill: currentColor;
	   overflow: hidden;
	 }
	</style>
  1. main.ts中配置
	import { createApp, Directive } from 'vue'
	import App from './App.vue'
	import "./icons"  //引入图标
	import SvgIcon from '@/components/SvgIcon/index.vue'  //引入图标组件
	
	const app = createApp(App)
	const req = require.context('@/icons/svg', false, /\.svg$/) 
	const requireAll = (requireContext: any) => requireContext.keys().map(requireContext)
	requireAll(req)   //自动引入 ./icons 下面所有的图标
	
	app.use(store).use(router).component('svg-icon', SvgIcon).mount('#app')
  1. 使用svg-sprite-loader对项目中使用的svg进行处理

npm install svg-sprite-loader --save-dev;
在vue.config.js文件中修改webpack的配置,vue2.0项目没有vue.config.js文件的话,在项目根目录创建vue.config.js,配置如下:

  chainWebpack: config => {
    // svg loader
    const svgRule = config.module.rule('svg') // 找到svg-loader
    svgRule.uses.clear() // 清除已有的loader, 如果不这样做会添加在此loader之后
    svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录
    svgRule // 添加svg新的loader处理
      .test(/\.svg$/)
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
    // 修改images loader 添加svg处理
    const imagesRule = config.module.rule('images')
    imagesRule.exclude.add(resolve('src/icons'))
    config.module
      .rule('images')
      .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
  }

至此,封装就已经结束了,让我们来验证一下封装的组件是否可行吧。

  1. 如何使用
<svg-icon class="nav-icon" iconClass="dashboard"/>
//iconClass属性的就是当前icon的名字;无需在页面中引入图片,直接使用即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值