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" />
相关推荐
NetX行者14 分钟前
用 Vite + Vue3 + UnoCSS 搭建企业级项目模板(一):基础骨架
vue·vite·unocss
软件技术NINI26 分钟前
圣罗兰彩妆html+css 4页
前端·css·html
2601_951615201 小时前
网站模板 网站网页模板下载
前端·网络·html
酷炫码神1 小时前
Day 1|HTML5:一个商城首页的骨架,从 DOCTYPE 到语义化
前端·html·html5
AI源码2 小时前
鲜花商城(HTML 版)
前端·html
hiahiahia1232 小时前
Message 和对话
服务器·前端·数据库
溪语流沙2 小时前
【Web全栈进阶】Composition API与组件通信:props深入、emit、插槽
前端·css·vue.js
ZoeLandia3 小时前
TypeScript 03:泛型与工具类型
前端·typescript
code_Bo3 小时前
从策划到上线:我和 AI 一起做了个微信记账小程序
前端·ai编程·cursor
Shirley~~3 小时前
Three.js加载Gltf模型并播放动画
前端·3d