vue3中使用插件vite-plugin-svg-icons

在vue3 + vite 项目中使用svg图标
插件:vite-plugin-svg-icons

  • 预加载 在项目运行时就生成所有图标,只需操作一次 dom
  • 高性能 内置缓存,仅当文件被修改时才会重新生成

安装

bash 复制代码
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

使用

  • vite.config.ts 中的配置插件
javascript 复制代码
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

plugins: [
  createSvgIconsPlugin({
    // 指定缓存文件
    iconDirs: [resolve(process.cwd(), "src/assets/icons/svg")],
    // 指定symbolId格式
    symbolId: "icon-[dir]-[name]",
  }),
]

配置 main.ts

javascript 复制代码
import 'virtual:svg-icons-register'

封装SvgIcon组件 src/components/SvgIcon

javascript 复制代码
<template>
  <div v-if="isExter" :style="styleExternalIcon" v-bind="$attrs" class="svg-external-icon svg-icon" />
  <svg v-else :class="svgClass" aria-hidden="true" v-bind="$attrs">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script setup lang="ts">
import { isExternal } from '@/utils/validate'
defineOptions({
  name: 'SvgIcon',
})

const props = withDefaults(defineProps<{
  iconClass: string,
  className?: string
}>(), {
  className: ''
})

const isExter = computed(() => {
  return isExternal(props.className)
})
const iconName = computed(() => {
  return `#icon-${props.iconClass}`
})
const svgClass = computed(() => {
  if (props.className) {
    return 'svg-icon ' + props.className
  } else {
    return 'svg-icon'
  }
})
const styleExternalIcon = computed(() => {
  return {
    mask: `url(${props.iconClass}) no-repeat 50% 50%`,
    '-webkit-mask': `url(${props.iconClass}) no-repeat 50% 50%`
  }
})
</script>

<style scoped lang="scss">
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover!important;
  display: inline-block;
}
</style>

组件使用

javascript 复制代码
<svg-icon icon-class="404" />
相关推荐
不羁的fang少年8 分钟前
前端常见问题(vue,css,html,js等)
前端·javascript·css
change_fate14 分钟前
el-menu折叠后文字下移
前端·javascript·vue.js
yivifu16 分钟前
CSS Grid 布局详解(2025最新标准)
前端·css
o***Z4482 小时前
前端性能优化案例
前端
张拭心2 小时前
前端没有实际的必要了?结合今年工作内容,谈谈我的看法
前端·ai编程
姜太小白2 小时前
【前端】CSS媒体查询响应式设计详解:@media (max-width: 600px) {……}
前端·css·媒体
HIT_Weston2 小时前
39、【Ubuntu】【远程开发】拉出内网 Web 服务:构建静态网页(二)
linux·前端·ubuntu
百***06012 小时前
SpringMVC 请求参数接收
前端·javascript·算法
天外天-亮2 小时前
Vue + excel下载 + 水印
前端·vue.js·excel
起个名字逛街玩2 小时前
前端正在走向“工程系统化”:从页面开发到复杂产品架构的深度进化
前端·架构