前端 Icon 图标处理方案

背景:使用vue3 + vue/cli + element-plus开发项目,icon图标分为两类:

  1. element-plus 的图标
  2. 自定义的 svg 图标

element-plus 的图标可以直接使用图标名称或者配合 el-icon 显示; 对于自定义图标,则需要一个自定义的组件。下面就是icon图标的一个解决方案:

在自定义组件中,需要考虑两种情况:

  1. 显示外部 svg 图标:通过style的mask: url(http://xxx/xxx.svg)

  2. 显示下载到本地的 svg 图标: 通过<svg>和<use>标签的结合

在components中创建文件:SvgIcon/index.vue

xml 复制代码
<template>
  <div
    v-if="isExternal"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    :class="className"
  ></div>
  <svg v-else class="svg-icon" :class="className" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script setup>
import { defineProps, computed } from 'vue'
import { isExternal as external } from '@/utils/validate'
const props = defineProps({
  icon: {
    type: String,
    required: true
  },
  className: {
    type: String,
    default: ''
  }
})

/**
 * 判断是否为外部图标
 */
const isExternal = computed(() => external(props.icon))

/**
 * 显示外部图标
 */
const styleExternalIcon = computed(() => ({
  mask: `url(${props.icon}) no-repeat 50% 50%`,
  '-webkit-mask': `url(${props.icon}) no-repeat 50% 50%`
}))

/**
 * 显示本地图标
 */
const iconName = computed(() => `#icon-${props.icon}`)
</script>

<style lang="scss" scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: middle;
  fill: currentColor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */
  overflow: hidden;
}
.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>

封装isExternal方法:创建 utils/validate.js

javascript 复制代码
//判断是否为外部资源
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

至此外部图标可以正常显示,以下是对于内部图标显示的处理

假设所有的本地图标xxx.svg都放在src/icons/svg目录中

在icons下创建index.js文件

javascript 复制代码
import SvgIcon from '@/components/SvgIcon'

// 通过 require.context() 函数来创建自己的 context
const svgRequire = require.context('./svg', false, /\.svg$/)

// 此时返回一个 require 的函数,可以接受一个 request 的参数,用于 require 的导入。
// 该函数提供了三个属性,可以通过 require.keys() 获取到所有的 svg 图标
// 遍历图标,把图标作为 request 传入到 require 导入函数中,完成本地 svg 图标的导入

svgRequire.keys().forEach(svgIcon => svgRequire(svgIcon))

export default app => {
  app.component('svg-icon', SvgIcon)
}

在main.js中引入

javascript 复制代码
// 导入 svgIcon
import installIcons from '@/icons'

installIcons(app)

至此图标还没办法显示,需使用svg-sprite-loader ,是 webpack 中专门用来处理 svg 图标的一个 loader

  1. 执行:npm i --save-dev svg-sprite-loader@6.0.9
  2. 在 vue.config.js 文件,新增如下配置:
lua 复制代码
const path = require('path')
function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = defineConfig({
  chainWebpack(config) {
    // 设置 svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  }
})

现在可以使用了,使用方式如下:

  1. 外部图标:
ini 复制代码
<span class="svg-container">
	<svg-icon icon="http://xxx/x.svg"></svg-icon>
</span>
  1. 本地图标
ini 复制代码
<svg-icon icon="user" />
相关推荐
tryCbest16 小时前
Vue系列——第 15 篇:内置组件全家桶——Transition、Teleport、Suspense、KeepAlive
前端·vue.js
徐小夕20 小时前
开源Vector-Graph-RAG:向量+图谱双引擎,打破纯向量RAG的效果天花板
前端·vue.js·github
FungLeo1 天前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome
FungLeo1 天前
成为全栈·Vue管理后台篇·<scriptsetup>:把页面拆成可读、可测的 Vue 组件
前端·javascript·vue.js·typescript·前端组件化·composition api·vue sfc
软件技术NINI2 天前
基于SpringBoot和Vue的新能源汽车销售推荐系统
java·vue.js·spring boot·后端·汽车·毕业设计·毕设
招风的黑耳2 天前
SpringBoot+Vue+MySQL 民宿在线预定平台 完整可运行版(源码+文档)
vue.js·spring boot·mysql
10share3 天前
基于大模型的 i18n 方案:把中文原文当 Key,轻松搞定多语言维护
前端·vue.js
啾咪orJIUMI3 天前
Vue 3 + 高德地图封装实战:点位、区域、Loca 流光与 Vue 信息窗体
前端·vue.js
FRing033 天前
vue2干货总结8(路由模块封装、router-link、声明式导航、路由重定向、编程式导航)
开发语言·前端·vue.js·vue2
无懈可击3 天前
Vue 可视化AI表单设计器 FcDesigner v3.6 版本发布,支持导出 SQL功能!
vue.js·开源·ai编程