前端开发必备: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'}"/>
相关推荐
LuHang4 分钟前
WebSocket服务封装实践:从连接管理到业务功能集成
前端·websocket
九十一5 分钟前
vue2中$set的原理
前端
闲不住的李先森11 分钟前
深入解析 Cursor 规则:为团队打造统一的 AI 编程规范
前端·ai编程·cursor
hsjkdhs15 分钟前
C++之多态
开发语言·jvm·c++
四维碎片18 分钟前
【Qt】乌班图安装Qt环境
开发语言·数据库·qt
kyle~22 分钟前
C++STL---静态数组array
开发语言·c++
FlowGram25 分钟前
FlowGram 官网建设
前端
晚枫~30 分钟前
零基础快速上手Playwright自动化测试
javascript·python·测试工具·c#·自动化
~无忧花开~31 分钟前
JavaScript学习笔记(二十八):JavaScript性能优化全攻略
开发语言·前端·javascript·笔记·学习·性能优化·js
BumBle32 分钟前
基于UniApp实现DeepSeek AI对话:流式数据传输与实时交互技术解析
前端·uni-app