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" />
相关推荐
XiaoSong1 天前
React useState 原理和异步更新
前端·react.js
徐徐子1 天前
从vue3 watch开始理解Vue的响应式原理
前端·vue.js
眯眼因为很困啦1 天前
GitHub Fork 协作完整流程
前端·git·前端工程化
whisper1 天前
🚀 React Router 7 + Vercel 部署全指南
前端
还债大湿兄1 天前
huggingface.co 下载有些要给权限的模型 小记录
开发语言·前端·javascript
叶落无痕521 天前
Electron应用自动化测试实例
前端·javascript·功能测试·测试工具·electron·单元测试
H@Z*rTE|i1 天前
elementUi 当有弹窗的时候提示语被覆盖的问题
前端·javascript·elementui
阿奇__1 天前
vue2+elementUI table多个字段排序
前端·javascript·elementui
hellokatewj1 天前
React Hooks 全解:原理、API 与应用场景
前端·javascript·react.js
袋鱼不重1 天前
保姆级教程:让 Cursor 编辑器突破地区限制,正常调用大模型(附配置 + 截图)
前端·后端·cursor