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" />
相关推荐
江号软件分享26 分钟前
有效保障隐私,如何安全地擦除电脑上的敏感数据
前端
web守墓人1 小时前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
Savior`L2 小时前
CSS知识复习5
前端·css
许白掰2 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
中微子6 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
中微子7 小时前
React 状态管理 源码深度解析
前端·react.js
加减法原则8 小时前
Vue3 组合式函数:让你的代码复用如丝般顺滑
前端·vue.js
yanlele9 小时前
我用爬虫抓取了 25 年 6 月掘金热门面试文章
前端·javascript·面试
lichenyang4539 小时前
React移动端开发项目优化
前端·react.js·前端框架
你的人类朋友9 小时前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维