前端开发必备: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'}"/>
相关推荐
Logan Lie几秒前
Go 反射(Reflection)详解:从入门到实践
开发语言·后端·golang
爱装代码的小瓶子2 分钟前
【c++进阶】c++11下类的新变化以及Lambda函数和封装器
java·开发语言·c++
m0_748250037 分钟前
C++ 标准库概述
开发语言·c++
FAFU_kyp8 分钟前
Rust 所有权(Ownership)学习
开发语言·学习·rust
古迪红尘9 分钟前
el-tree 采用懒加载方式,怎么初始化就显示根节点和下级节点
前端·javascript·vue.js
糖墨夕12 分钟前
当代码照进生活:一个程序员眼中的欲望陷阱
前端
superman超哥14 分钟前
Rust 异步性能的黑盒与透视:Tokio 监控与调优实战
开发语言·后端·rust·编程语言·rust异步性能·rust黑盒与透视·tokio监控与调优
Aotman_16 分钟前
Vue el-table 字段自定义排序(进阶)
前端·javascript·vue.js·elementui·前端框架·ecmascript
Charonrise16 分钟前
完美解决Microsft Edge浏览器双击无法打开 双击无反应 无响应 不能用
前端·edge
华仔啊17 分钟前
这 5 个冷门 HTML 标签,让我直接删了100 行 JS 代码!
前端·html