vite+vue3展示文件夹内的所有组件
https://www.cnblogs.com/y-shmily/p/16546743.html
在组件目录下新建index.js
import { markRaw } from "vue"; const filesNameList = []; const files = import.meta.glob("./*.vue"); for (const key in files) { const fileName = key.replace(/(\.\/|\.vue)/g, ""); filesNameList.push(fileName); } // 导出当前目录下的所有.vue的文件 export default markRaw(filesNameList);
展示所有组件 index.vue
<template> <div class="drag-box"> <div class="head"> <h3>组件列表</h3> </div> <div class="compList"> <!-- 渲染所有组件 --> <el-card class="items" shadow="hover" v-for="element in componentList" :key="element.FileName" > <div class="title"><b>组件名: </b>{{ element.FileName }}</div> <div class="compMian"> <component :is="element.component"></component> </div> </el-card> </div> </div> </template> <script setup> import { ref, defineAsyncComponent, markRaw } from "vue"; // 引入modules目录下所有的模板名称数组 import allComps from "./modules"; const componentList = ref([]); allComps.map((v) => { let item = { FileName: "", component: null, }; item.FileName = v; // 导入组件 item.component = markRaw( defineAsyncComponent(() => import(`./modules/${v}.vue`)) ); // 组件列表追加组件信息 componentList.value.push(item); }); </script> <style lang="less" scoped> .drag-box .items { width: 100%; margin: 20px 0; border-bottom: solid 1px #999; // background-color: #eee; .title { font-size: 18px; line-height: 1.5; margin-bottom: 25px; border-bottom: solid 1px #eee; b { font-size: 22px; } } .compMian { background-color: #fff; } } </style>
目录结构
import { markRaw } from "vue";
const filesNameList = [];
const files = import.meta.glob("./*.vue");
for (const key in files) {
const fileName = key.replace(/(\.\/|\.vue)/g, "");
filesNameList.push(fileName);
}
// 导出当前目录下的所有.vue的文件
export default markRaw(filesNameList);