这篇文章教会你如何封装一个svg-icon组件,这个组件在后续的button等组件中也用到了。
插件安装 vite-plugin-svg-icons - npm
在封装我们自己的svg组件之前我们需要使用插件导入svg文件,这样方便我们后续通过元素id进行全局使用svg,使用插件vite-plugin-svg-icons。
插件用法
- vite项目中安装该插件 pnpm i vite-plugin-svg-icons -D
- 在vite中配置 svg在项目中的什么位置
- createSvgIconsPlugin函数:iconDirs、symbolId(配置这两个就行)
import path from 'path'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), './src/assets/icons')], // 指定svg存放的路径
symbolId: 'icon-[name]' // 指定svg的id
})
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
})
上面配置的内容如下所示:
这样在项目中就给svg添加了对应的id, id 是 icon-name,name是svg名字。
组件封装
在svg-icon组件中我们需要考虑组件暴露的内容,方便我们使用组件。上面那个插件可以根据id获取svg文件。所以定义了一下对外暴露的配置。
- name :svg文件的名字
- color:自定义的svg的填充颜色
- fillClass(用于tailwindcss的):用于直接使用tailwindcss的样式类名的,便于扩展
<template>
<svg aria-hidden="true">
<use :class="fillClass" :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
name: {
type: String,
required: true
},
color: {
type: String
},
fillClass: {
type: String
}
})
const symbolId = computed(() => `#icon-${props.name}`)
</script>
<style lang='scss' scoped></style>
组件自动挂载
在封装了这个插件之后,在项目中导入使用,以前我们是用到一个导入一个。现在有个简便的方法,就是自动挂载全局组件。
核心原理:
使用vite提供的import.meta.glob读取组件内容,然后进行挂载
组件使用案例
<svg-icon v-if="loading" name="loading" class=" w-2 h-2 animate-spin mr-1"></svg-icon>
使用了name为loading'的svg文件封装的一个loading图标的组件