# vue3+vite+ts-SvgIcon组件

# 1.装vite-svg-icon

npm i vite-svg-icon

# 2.vite.config.ts引入

import { svgBuilder } from "vite-svg-icon";

// 使用插件
plugins: [vue(), svgBuilder("./src/assets/svg/")]

TIP

svgBuilder 里面的参数即存放要使用的svg文件路径

# 3.src/components下新建

新建SvgIcon文件夹并包含index.ts和index.vue.ts

<!--index.ts-->
import SvgIcon from "@/components/SvgIcon/index.vue";

export default (app: any) => {
	app.component("SvgIcon", SvgIcon);
};
<!--index.vue-->

<template>
    <span class="svg-icon">
        <svg :class="$attrs.class" aria-hidden="true" style="width: 1em; height: 1em; vertical-align: -0.15em; overflow: hidden">
            <use :xlink:href="symbolId" :fill="color" />
        </svg>
    </span>
</template>

<script setup lang="ts">
import { computed } from "vue";

const props = defineProps({
    prefix: {
        type: String,
        default: "icon",
    },
    name: {
        type: String,
        required: true,
    },
    color: {
        type: String,
        default: "#333",
    },
});

const symbolId = computed(() => `#${props.prefix}-${props.name}`);
</script>

<style lang="less" scoped></style>

# 4.main.ts全局注册使用

// install svgIcons
import InstallIcon from "@/components/svgIcon/index";

const app = createApp(App);

// 全局注册SvgIcon组件
InstallIcon(app)

# 5.使用示例

可以自行添加class 或者style

<SvgIcon name="voice" />

<svg-icon name='icon' />
Last Updated: 3/22/2023, 10:47:20 PM