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图标组件
* @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图标为组件
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({
// 要缓存的图标文件夹
iconDirs: [path.resolve(__dirname, 'src/assets/svg')],
// 执行 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)