1.安装vite-plugin-svg-icons插件
npm i vite-plugin-svg-icons -D
2.在vite.config.ts中配置
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default defineConfig({
plugins: [
createSvgIconsPlugin({
// 要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// 执行 icon name 的格式
symbolId: 'icon-[dir]-[name]'
})
]
})
3.创建SvgIcon文件,在components目录下创建SvgIcon文件,
/components/SvgIcon/index.vue
<template>
<svg :style="{width,height}">
<use :xlink:href="preix+iconName" :fill="color"></use>
</svg>
</template>
<script setup lang="ts">
defineProps({
preix:{
type:String,
default:"#icon-"
},
iconName:{
type:String
},
color:{
type:String
},
width:{
type:String,
default:"16px"
},
height:{
type:String,
default:"16px"
}
})
</script>
5.直接引入使用即可
<template>
<svg-icon iconName="down" width="100px" height="100px" color="pink"></svg-icon>
</template>
<script setup lang="ts">
import SvgIcon from '@/components/SvgIcon/index.vue'
</script>
但是还没完,这种的一般都是全局引入使用,有两种方法:
1.在main.ts中全局引入
import SvgIcon from '@/components/SvgIcon/index.vue'
app.component('SvgIcon',SvgIcon)
2.在components目录下创建index.ts文件
//有需要全局调用的组件都可以引入进来
import SvgIcon from '@/components/SvgIcon/index.vue'
const allGloablComponent = {SvgIcon}
export default {
install(app){
Object.keys(allGloablComponent).forEach(key=>{
app.component(key,allGloablComponent[key])
})
}
}
在main.ts文件中引入
import GloalComponent from '@/components'
app.use(GloalComponent)
好了,完事了