vite+vue3统一引入svg,全局挂载组件使用

435 阅读1分钟

vite+vue3统一引入svg,全局挂载组件使用

项目中有很多svg图标,较多页面使用,如果一个一个引入使用那就太麻烦了

这里记录一下使用插件引入,挂载全局组件吧

文档地址: github.com/vbenjs/vite…

特征

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

安装

node version:  >=12.0.0

vite version:  >=2.0.0

yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

使用插件全局导入

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

//vite.config.ts中配置plugins

createSvgIconsPlugin({
  //指定 SVG 图标文件所在的目录。
  iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
  //定义图标id
  symbolId: 'icon-[dir]-[name]',
  svgoOptions: false
})

在 src/main.ts 内引入注册脚本

import 'virtual:svg-icons-register'

Vue组件

/src/components/SvgIcon.vue

<template>
  <svg :class="svgClass">
    <use :xlink:href="iconName" :fill="color" />
  </svg>
</template>

<script setup>
const props = defineProps({
  iconClass: {
    type: String,
    required: true
  },
  className: {
    type: String,
    default: ''
  },
  color: {
    type: String,
    default: ''
  }
})
const iconName = computed(() => `#icon-${props.iconClass}`)
const svgClass = computed(() => {
  if (props.className) {
    return `svg-icon ${props.className}`
  }
  return 'svg-icon'
})
</script>

<style scope lang="less">
.sub-el-icon,
.nav-icon {
  display: inline-block;
  font-size: 15px;
  margin-right: 12px;
  position: relative;
}

.svg-icon {
  width: 1em;
  height: 1em;
  position: relative;
  fill: currentColor;
  vertical-align: -2px;
}
</style>

  • 全局挂载组件
import SvgIcon from '@/components/SvgIcon/index.vue'
app.component('SvgIcon', SvgIcon)
  • 使用
<svg-icon :icon-class="401" class-name="icon" style="width: 16px; height: 25px" />

展示出来就是401的图标, 401是文件名称,

如果想要将svg文件分类存放

那么目录是这样的

#src/asset
svg
    tips
        tip_01.svg
        tip_02.svg
    homes
        home_01.svg
        home_02.svg

使用的时候拼接上路径

<svg-icon
    :icon-class="'tips-tips_01'"
    class-name="icon"
    style="width: 16px; height: 25px"
/>