一、基础例子
<template>
<div>
<!-- 使用 v-if 或 v-show 控制组件的显示 -->
<component v-if="isLazyComponentVisible" :is="currentComponentName"></component>
</div>
</template>
<script>
export default {
data() {
return {
isLazyComponentVisible: false, // 控制组件是否可见的变量
currentComponentName: 'LazyLoadedComponent' // 当前需要加载的组件名
};
},
// 使用动态导入实现懒加载
async created() {
const LazyLoadedComponent = await import('./LazyLoadedComponent.vue'); // 动态导入组件
this.currentComponentName = LazyLoadedComponent.default.name; // 设置当前需要加载的组件名
this.isLazyComponentVisible = true; // 设置组件可见,开始渲染组件
}
};
</script>
二、项目中应用
使用懒加载按需加载组件,减少初始加载的时间,解决页面初始化加载慢问题,提高页面的响应速度,用户体验好。(这里是我在项目中使用仅供参考~)
效果图:
<component
v-if="haveData"
:index="activeName"
:is="active" //当前组件名
:dataObject="chargeObject"
:flow="instanceId"
/>
export default {
data() {
return {
haveData: false, // 是否有数据
active:'', //组件名
};
},
created() {
//获取到component{}里面的组件名(eg:PURCHASE)这样它就会去匹配里面的组件加载
let type = covertDic('reimType',this.$route.query.workFlowKey)//从路由拿key
if (type) {
//通过workflowkey去获取名字
this.active = type;
this.instanceId = this.$route.query.instanceId
localStorage.setItem('title',this.$route.query.title);
}else{
this.$toast("获取报销类型失败");
}
this.getTabData(); //基本信息
this.flow(); //流转信息
},
components: {
Nav,
PURCHASE: () => import('./expense/PURCHASE.vue'), // 非合同采购 --
TRAVEL: () => import('./expense/TRAVEL.vue'), // 差旅费 --
MEETING: () => import('./expense/MEETING.vue'), //会议费 --
DIRECT: () => import('./expense/DIRECT.vue'), //直接报销 --
GENERAL: () => import('./expense/GENERAL.vue'), //一般经费 --
......
},
2、component 组件
3、导入的组件内传数据过去(eg:PURCHASE.vue组件)
props: ["index", "dataObject","flow"],
4、utils封装的方法
function covertDic(name,key){
let dic = {
//报销的类型转换
reimType:{
'LABOR_COST_REIMBURSEMENT':'SERVICE',
'TRAVEL_REIMBURSEMENT':'TRAVEL',
'BUSINESS_RECEPTION_REIMBURSEMENT':'OFFICIAL',
'REIMBURSEMENT_TRAINING':'TRAINING',
//合同报销
"CONTRACT_REIMBURSEMENT":'CONTRACT',
// 直接
'DIRECT_REIMBURSEMENT':'DIRECT',
// 非合同报销
'INCONTRACT_REIMBURSEMENT':'PURCHASE',
// 会议费
'MEETING_REIMBURSEMENT':'MEETING'
},
....................
}
if(dic[name]){
return dic[name][key]
}
}