1. 增加svg組件
<template>
<svg
class="svg-icon"
aria-hidden="true"
:style="{
width: props.size + 'px',
height: props.size + 'px',
color: props.color
}"
>
<use :xlink:href="`#icon-${props.name}`" :fill="props.color" />
</svg>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
/**
* @description: svg圖標(biāo)組件
* @use {*} <SvgIcon name="home" :size="14" color="red" />
*/
export default defineComponent({
name: 'SvgIcon',
props: {
name: {
type: String,
required: true
},
size: {
type: Number,
default: 14
},
color: {
type: String,
default: '#000'
}
},
setup(props) {
return {
props
}
}
})
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: middle;
fill: currentColor;
overflow: hidden;
}
</style>
2. 安裝插件 npm i vite-plugin-svg-icons --save-dev
3. 修改 vite.config.js 配置文件
// 配置全局加載svg圖標(biāo)為組件
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import path from 'path';
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
// 要緩存的圖標(biāo)文件夾
iconDirs: [path.resolve(__dirname, 'src/assets/svg')],
// 執(zhí)行 icon name 的格式
symbolId: 'icon-[name]'
})
]
})
4. main.ts
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// svg組件
import 'virtual:svg-icons-register'
import SvgIcon from './SvgIcon.vue'
app.component('SvgIcon', SvgIcon)