前端开发必备: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'}"/>
相关推荐
未来龙皇小蓝37 分钟前
RBAC前端架构-04:设置代理及开发配置
前端·vue.js
祈安_44 分钟前
深入理解指针(一)
c语言·前端
Tony Bai1 小时前
Go 1.26 :go mod init 默认行为的变化与 Go 版本管理的哲学思辨
开发语言·后端·golang
SuperEugene1 小时前
对象数组的排序与分组:sort / localeCompare / 自定义 compare
前端·javascript·面试
xyq20241 小时前
WebForms SortedList 深度解析
开发语言
Hx_Ma161 小时前
测试题(三)
java·开发语言·后端
CHANG_THE_WORLD2 小时前
深入理解C语言指针:从源码到汇编的彻底剖析
c语言·开发语言·汇编
星火开发设计2 小时前
序列式容器:deque 双端队列的适用场景
java·开发语言·jvm·c++·知识
码农葫芦侠2 小时前
Rust学习教程2:基本语法
开发语言·学习·rust
扶苏10022 小时前
“解构”与“响应”的博弈——深入剖析 Vue 3 的 toRef 与 toRefs
前端·javascript·vue.js