您的位置:首页 > 文旅 > 旅游 > Vue3+TS项目封装SVG图标显示组件vite-plugin-svg-icons插件使用

Vue3+TS项目封装SVG图标显示组件vite-plugin-svg-icons插件使用

2024/10/5 23:26:33 来源:https://blog.csdn.net/qq_35641191/article/details/142149894  浏览:    关键词:Vue3+TS项目封装SVG图标显示组件vite-plugin-svg-icons插件使用

准备好svg文件 

假设从iconfont-阿里巴巴矢量图标库下载了一个svg格式的图标,放在我们项目里,并重命名为ic_money.svg,相对路径为:src\assets\images\icons\ic_money.svg

 安装vite-plugin-svg-icons插件

npm install vite-plugin-svg-icons -Dnpm install vite-plugin-svg-icons@2 -D // 安装指定版本

本例插件版本如下

"vite-plugin-svg-icons": "^2.0.1"

 vite.config.ts中加入以下代码

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'const svgIconsPlugin = createSvgIconsPlugin({iconDirs: [path.resolve(process.cwd(), 'src/assets/images/icons')],symbolId: 'icon-[dir]-[name]',
});export default defineConfig({plugins: [...svgIconsPlugin,],...
})

新建SvgIcon.vue文件

在src\components目录下新建组件:SvgIcon.vue

<template><svg :style="iconStyle" aria-hidden="true"><use :xlink:href="iconUrl" :fill="color"/></svg>
</template>
<script lang="ts" setup>
import { computed } from 'vue';const props = defineProps({name: {type: String,default: '',},size: {type: String,default: '14',},color: {type: String,default: '#3f99fa',},
})
const iconUrl = `#icon-${props.name}`;
const iconStyle = computed(() => {return {height: `${props.size}px`,width: `${props.size}px`,};
})
</script>
<style scoped>
</style>

main.ts中将SvgIcon注册为全局组件 

import 'virtual:svg-icons-register';
import SvgIcon from "@/components/SvgIcon.vue";const app = createApp(App)app.component("SvgIcon", SvgIcon);

页面中使用SvgIcon

// template中
<SvgIcon name="ic_money" size="20" color="#fbd95d"></SvgIcon>// js中 导入组件
import SvgIcon from '@/components/SvgIcon.vue'

效果

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com