前端开发必备: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'}"/>
相关推荐
江华森11 分钟前
云原生从0到1:Kubernetes 工作负载实战——Deployment/Service/滚动更新/弹性伸缩
前端·后端
江华森18 分钟前
《云原生从0到1:4台华为云ECS搭建Kubernetes 1.28集群实录(上)——环境与踩坑全记录》
前端·后端
captain37619 分钟前
文件与IO(2)
java·开发语言·windows·java-ee
codeY22 分钟前
Vite 前端发布后「点击菜单没反应」?旧版本资源 404 的完整排查与修复实录
前端·前端工程化
90后的晨仔40 分钟前
uni-app Vue3 状态管理 Pinia 完全指南:从概念到实战的深度解析
前端
mqiqe40 分钟前
AgentScope Java 2.0 集成 Chat Completions Web:一行依赖让你的 Agent 变身 OpenAI 兼容服务
java·开发语言·前端
程序员小八77741 分钟前
后端开发初学TypeScript
前端·javascript·typescript
90后的晨仔43 分钟前
Puppeteer 与 Playwright 深度实战指南:从零到精通,全面提升开发效率
前端
qq_589666051 小时前
Java微服务介绍及应用
java·开发语言·微服务
sunphp开发者1 小时前
阿里云CDN加速配置问题
前端·阿里云·云计算