vue3+vite使用svg图标

67 阅读1分钟

一,安装SVG依赖插件

pnpm install vite-plugin-svg-icons -D

二,在vite.config.ts中配置插件

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
  return {
    plugins: [
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
  }
}

三,入口文件导入

import 'virtual:svg-icons-register'

4 在src/assets文件下新建文件夹icons,引入xxx.svg文件

5、svg封装为全局组件

<template>
  <svg :style="iconStyle" aria-hidden="true">
    <use :xlink:href="symbolId" />
  </svg>
</template>

<script setup lang="ts" name="SvgIcon">
import { computed, CSSProperties } from 'vue'

interface SvgProps {
  name: string // 图标的名称 ==> 必传
  prefix?: string // 图标的前缀 ==> 非必传(默认为"icon")
  iconStyle?: CSSProperties // 图标的样式 ==> 非必传
}
// 接收父组件参数并设置默认值
const props = withDefaults(defineProps<SvgProps>(), {
  prefix: 'icon',
  iconStyle: () => ({ width: '28px', height: '28px' })
})

const symbolId = computed(() => `#${props.prefix}-${props.name}`)
</script>
// main.js
import SvgIcon from './SvgIcon/index.vue';
app.component('SvgIcon', SvgIcon);

6.使用

<SvgIcon class="mr-6" name="xxx" :iconStyle="{ width: '1rem', height: '1rem' }" />