前端开发必备:icon封装技巧

main.js
复制代码
import svgIcon from '@/components/SvgIcon'
Vue.component('svg-icon-full', svgIcon)
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('@/assets/icons/svg', false, /\.svg$/)  // icon位置
requireAll(req)
SvgIcon组件
复制代码
<template>
  <i v-if="iconFileName.indexOf('el-icon-') === 0" :class="iconFileName" />
  <svg v-else class="svg-icon" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="`#icon-${iconFileName}`" rel="external nofollow" :class="[iconColor]"/>
  </svg>
</template>

<script>
export default {
  name: 'SvgIcon',
  props: {
    iconFileName: {
      type: String,
      required: true
    },
    iconColor: {
      type: String,
      default: ''
    }
  }
}
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  overflow: hidden;
  vertical-align: -0.15em;
  fill: currentColor;
}
</style>
SvgIcon调用

icon-file-name="文件名"

复制代码
<svg-icon-full icon-file-name="alarm" :style="{width: '14px', height: '14px', color: '#FF4621'}"/>
相关推荐
freewlt7 小时前
前端性能优化实战:从 Lighthouse 分数到用户体验的全面升级
前端·性能优化·ux
0xDevNull7 小时前
Java反射机制深度解析:从原理到实战
java·开发语言·后端
小小亮017 小时前
Next.js基础
开发语言·前端·javascript
华洛7 小时前
我用AI做了一个48秒的真人精品漫剧,不难也不贵
前端·javascript·后端
ALex_zry7 小时前
C++网络编程心跳机制与连接保活:长连接稳定性保障
开发语言·网络·c++
Amumu121388 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
Novlan18 小时前
我把 Claude Code 里的隐藏彩蛋提取出来了——零依赖的 ASCII 虚拟宠物系统
前端
Sgf2278 小时前
ES8(ES2017)新特性完整指南
开发语言·javascript·ecmascript
IAUTOMOBILE8 小时前
Python 流程控制与函数定义:从调试现场到工程实践
java·前端·python
好大哥呀8 小时前
C++ Web 编程
开发语言·前端·c++