🌬🌬🌬前言:我们都知道前端直接面临的是大众的视觉挑战,平时比较常见的是前/后台系统,后台系统的特点是样式同质化高,而前台系统的特点是个性化样式,无论是前台/后台系统,不仅要给用户带来更好的视觉体验还要考虑到用户的日常操作习惯,除了考验我们的设计同学外,前端同学也要针对不同场景的系统进行区别处理,当然现在市场上有很多成熟的组件库比如:Element 、Ant,物料库:Taro、物料中心,当然也有公司存在个性化设计主题,所以需要自行开发内部通用组件库,下面是基于Vue3+Vite+Tailwind封装的一些通用组件分享,大家有更好的提议,欢迎评论区留言哈👏👏👏
一、构建基础列表
大致目录结构
---| src
---| libs // 通用组件
---|---| svg-icon // 矢量图组件
---|---| waterfall // 瀑布流组件
---| utils // 工具类
---| api // 接口api集合
---|---| pexels.js // 图片接口api(图片来源pexel)
---|---| assets // 静态资源
---|---| views // 视图
---|---|---| main
---|---|---|---| index.vue
---|---|---|---| components
---|---|---|---|--| list // 列表组件
---|---|---|---|--|---| index.vue // 列表展示组件
---|---|---|---|--|---| item.vue // item 的视图组件
1. 创建 src/libs/svg-icon/index.vue
<template>
<svg aria-hidden="true">
<use :class="fillClass" :xlink:href="symbolId" :fill="color"></use>
</svg>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
// 显示的 svg 图标名称
name: {
type: String,
required: true
},
// svg 图标的颜色
color: {
type: String
},
// 通过 tailwind 指定 svg 颜色的类名
fillClass: {
type: String
}
})
// 真实显示的 svg 图标名字(拼接 #icon-)
const symbolId = computed(() => `#icon-${props.name}`)
</script>
2. 组件注册src/libs/index.js
🍭🍭🍭PS:由于我们后面还有其他组件需要注册,所以我们可以用vite 提供的功能,进行通用组件的自动化注册,涉及到的知识点如下:
- 🍬vite 的 Glob 导入:该功能可以帮助我们在 文件系统中导入多个模块
- 🍬vue 的 defineAsyncComponent():该方法可以创建一个 按需加载的异步组件
import { defineAsyncComponent } from 'vue'
export default {
install(app) {
// 获取当前路径任意文件夹下的 index.vue 文件
const components = import.meta.glob('./*/index.vue')
// 遍历获取到的组件模块
for (const [key, value] of Object.entries(components)) {
// 拼接组件注册的 name
const componentName = 'm-' + key.replace('./', '').split('/')[0]
// 通过 defineAsyncComponent 异步导入指定路径下的组件
app.component(componentName, defineAsyncComponent(value))
}
}
}
3. vite 处理 svg 矢量图
🎈🎈🎈PS:由于vite不会处理咱们主动导入的 svg 矢量图标,所以我们需要借助 vite 的 plugin vite-plugin-svg-icons
- 安装
vite-plugin-svg-icons
npm i --save-dev vite-plugin-svg-icons@2.0.1
import path, { join } from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig ({
plugins: [
vue(),
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// 指定symbolId格式
symbolId: 'icon-[name]'
})
]
})
- main.js
import mLibs from './libs' // 导入
import 'virtual:svg-icons-register' // 虚拟路径
// use 注册
createApp(App).use(mLibs).use(router).use(store).mount("#app");
3. 使用 demo.vue
<template>
<!-- 加载更多 -->
<m-svg-icon
v-show="loading"
class="w-4 h-4 mx-auto animate-spin"
name="infinite-load"
></m-svg-icon>
<!-- 反馈 -->
<m-svg-icon
name="feedback"
class="w-2 h-2"
fillClass="fill-zinc-900 dark:fill-zinc-200 group-hover:fill-main "
></m-svg-icon>
...
</template>
至此我们的svg-icon 组件就已经构建并且使用完成啦🎆🎆🎆,下一节我们再来分享~🎈🎈🎈
![](https://img.haomeiwen.com/i4578791/de1a722a613dc316.png)
网友评论