vue3+vite使用svg图标

109 阅读1分钟

下载插件vite-plugin-svg-icons

yarn add vite-plugin-svg-icons -D  //下载依赖包
配置vite.config.ts
export default defineConfig({
  plugins: [vue(),
        createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹,即图标放置位置
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
        // 指定symbolId格式,相当于唯一标识,也可以写成icon-[name]等等,[name]这样写代表是name变量,这个必须以含有[name]的字符串当作唯一标识不然会报错
        symbolId: '[name]',
        /**
         * 自定义插入位置
         * @default: body-last
         */
        // inject?: 'body-last' | 'body-first'

        /**
         * custom dom id
         * @default: __svg__icons__dom__
         */
        // customDomId: '__svg__icons__dom__',
        })
  ]
  })
创建svg组件
<template>
    <svg aria-hidden="true" class="svg-icon" :width="props.width" :height="props.height">
        <use :xlink:href="symbolId" :fill="props.color" />
    </svg>
</template>

<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
    width: string,
    height: string,
    color: string,
    name: string
}>()
const symbolId = computed(() => `#${props.name}`)

</script>

<style scoped></style>
全局注册svg组件
import 'virtual:svg-icons-register' //引入插件
import SvgIcon from '@/components/SvgIcon.vue'
const app = createApp(App)
app.component('svg-icon', SvgIcon)
使用
//这里传递的name为想要渲染的svg文件名字
<svg-icon name="title" width="104px" height="24px" />