Vue3中级指南-如何在vite中使用svg图标

发布时间 2023-08-02 11:25:15作者: 龙果果

 

vite-plugin-svg-icons

  • 预加载 在项目运行时就生成所有图标,只需操作一次 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

使用

vite.config.js中的配置插件

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
  return {
    plugins: [
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',

        /**
         * 自定义插入位置
         * @default: body-last
         */
        // inject?: 'body-last' | 'body-first'

        /**
         * custom dom id
         * @default: __svg__icons__dom__
         */
        // customDomId: '__svg__icons__dom__',
      }),
    ],
  }
} 

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

import 'virtual:svg-icons-register'

 

创建SvgIcon组件

/src/components/SvgIcon/index.vue

<template>
  <svg
    aria-hidden="true"
    class="svg-icon"
    :width="props.size"
    :height="props.size"
  >
    <use :xlink:href="symbolId" :fill="props.color" />
  </svg>
</template>
<script setup>
  import { computed } from 'vue'
  const props = defineProps({
    prefix: {
      type: String,
      default: 'icon'
    },
    name: {
      type: String,
      required: true
    },
    color: {
      type: String,
      default: '#333'
    },
    size: {
      type: String,
      default: '1em'
    }
  })
  const symbolId = computed(() => `#${props.prefix}-${props.name}`)
  // const symbolId = computed(() => `#${props.name}`)
</script>
全局注册组件

# src/main.js

import SvgIcon from "@/components/SvgIcon/index.vue";
import 'virtual:svg-icons-register'

reateApp(App)     
    .component('SvgIcon', SvgIcon)
    .mount('#app')
icons目录结构

# src/icons

- wind-turbine.svg

- icon2.svg

- icon3.svg 

页面使用
<SvgIcon name="wind-turbine" color="#fff" size="44px" />

 

获取所有 SymbolId

import ids from 'virtual:svg-icons-names'
// => [    "icon-guangfu-fadian",    "icon-wind-turbine"    ]