vue3,vite使用svg,使用vite-plugin-svg-icons插件

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)

好了,完事了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值