vue3.0页面动态引入指定目录下部件并动态加载部件,无需页面手动单个export
1.添加index.js文件读取引入指定目录下的vue部件页面(自动扫描目录下所有.vue 文件,自动导出)
// src/components/index.js // 自动扫描当前目录下所有.vue组件,无需手动写export // 1. 动态获取所有.vue组件(Webpack/Vite都支持) const components = import.meta.glob('../components/*.vue', { eager: true }) // Vite 写法 // 如果是Webpack/Vue2,替换成: // const components = require.context('.', false, /\.vue$/) // 2. 自动构建导出对象 const exportObj = {} for (const path in components) { // 提取组件名(比如 ./OverviewCover.vue → OverviewCover) const componentName = path.replace(/^\.\//, '').replace(/\.vue$/, '') // 导出组件(Vite) exportObj[componentName] = components[path].default // Webpack/Vue2 替换成: // exportObj[componentName] = components(path).default } // 3. 批量导出所有组件 export default exportObj
2.使用页面引入js文件并页面根据key动态显示相应模板页
原先冗余代码:
//1.页面需要使用几个部件,需要全部引入 import OverviewCover from "../components/OverviewCover.vue"; import CurRoomStatusData from "../components/CurRoomStatusData.vue"; import AreaRoomStata from "../components/AreaRoomStata.vue"; import BuildDeviceUseTime from "../components/BuildDeviceUseTime.vue"; import BuildDeviceUseTimeTrendAnaly from "../components/BuildDeviceUseTimeTrendAnaly.vue"; import SystemBasicInfo from "../components/SystemBasicInfo.vue"; //2.构建部件映射键值对,通过key来指定显示相应模板页 const componentMap = { OverviewCover: OverviewCover, CurRoomStatusData: CurRoomStatusData, AreaRoomStata: AreaRoomStata, BuildDeviceUseTime: BuildDeviceUseTime, BuildDeviceUseTimeTrendAnaly: BuildDeviceUseTimeTrendAnaly, } //3.页面根据key字段值动态显示 <div v-if="dialog.compent?.key != ''" class="detail-content"> <component :is="componentMap[dialog.compent?.key]" v-if="componentMap[dialog.compent?.key]" v-bind="{ screenmodel: dialog.compent.model, current_term: current_term, }" /> </div>
优化后:
引入js将指定目录下部件全部引入至页面中,并构建键值对,支持部件key动态加载组件;
import * as ScreenComponents from "./index"; const realComponentData = ScreenComponents.default || {}; const componentMap = {}; // 遍历realComponentData的所有属性(组件路径) Object.keys(realComponentData).forEach((componentPath) => { // console.error(componentPath, "componentPath"); // 每个组件的信息对象 const componentInfo = realComponentData[componentPath]; // 确保有name字段 if (componentInfo?.__name) { // 构建componentMap:key是name,值是组件信息 componentMap[componentInfo.__name] = componentInfo; } });
页面根据key动态加载部件
// v-bind 绑定部件要传的参 //:is和v-if 从componentMap根据部件key取出部件 <div v-if="dialog.compent?.key != ''" class="detail-content"> <component :is="componentMap[dialog.compent?.key]" v-if="componentMap[dialog.compent?.key]" v-bind="{ screenmodel: dialog.compent.model, current_term: current_term, }" /> </div>
本文来自博客园,作者:じ逐梦,转载请注明原文链接:https://www.cnblogs.com/ZhuMeng-Chao/p/19473002

浙公网安备 33010602011771号