1.通过pnpm安装引入svg需要用的插件
pnpm i vite-plugin-svg-icons
2.在vite.config.ts中配置
export default defineConfig({
plugins: [
//此处省略代码。。。
//icon全局配置
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]',
}),
//此处省略代码。。。
],
})
3.封装icon全局组件
// component/SvgIcon/index.vue
<template>
<!-- svg:图标外层容器节点,内部需要与use标签结合使用 -->
<svg :style="{ width, height }">
<!-- xlink:href执行用哪一个图标,属性值务必#icon-图标名字 -->
<!-- use标签fill属性可以设置图标的颜色 -->
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</template>
<script setup lang="ts">
//接受父组件传递过来的参数
defineProps({
//xlink:href属性值前缀
prefix: {
type: String,
default: '#icon-'
},
//提供使用的图标名字
name: String,
//接受父组件传递颜色
color: {
type: String,
default: ''
},
//接受父组件传递过来的图标的宽度
width: {
type: String,
default: '16px'
},
//接受父组件传递过来的图标的高度
height: {
type: String,
default: '16px'
}
})
</script>
<style scoped></style>
4.注册成全局组件
//component/index.ts
//引入项目中全部的全局组件
import SvgIcon from './SvgIcon/index.vue';
//全局对象
const allGloablComponent: any = { SvgIcon };
//对外暴露插件对象
export default {
//务必叫做install方法
install(app: any) {
//注册项目全部的全局组件
Object.keys(allGloablComponent).forEach(key => {
//注册为全局组件
app.component(key, allGloablComponent[key]);
});
}
}
5.在main.ts中配置
import { createApp } from 'vue'
//svg插件需要配置代码
import 'virtual:svg-icons-register'
//引入自定义插件对象:注册整个项目全局组件
import gloalComponent from '@/components'
const app = createApp(App)
//安装自定义插件
app.use(gloalComponent)
app.mount('#app')
6.去下载或复制svg图标在
/assets/icons/
7.使用
<svg-icon name="swtIcon" width="10px" height="10px"></svg-icon>
本文介绍了如何使用pnpm安装SVG图标插件,配置Vite以全局引入并注册SVG图标组件,以及在项目中使用和注册SVGIcon组件的过程。

778

被折叠的 条评论
为什么被折叠?



