vue实现按需加载组件及异步组件功能

2020-06-13 10:17:39易采站长站整理

说实话,我一开始也不知道什么叫按需加载组件,组件还可以按需加载???后来知道了

学不完啊…没关系,看我的

按需加载组件,或者异步组件,主要是应用了component的 is 属性

template中的代码:

这里的每一个按钮,都要显示不同的组件,所以我让他们使用了同一个方法名


<template slot-scope="scope">
<el-button
type="text"
size="mini"
@click="handleSchedule('CustomerInfoSchedule', scope.row.customer_id)"
>详情</el-button>
<el-button
type="text"
size="mini"
@click="handleSchedule('VisitRecordSchedule', scope.row.customer_id)"
>回访</el-button>
<el-button
type="text"
size="mini"
@click="handleSchedule('AddCustomerSchedule',scope.row.customer_id)"
>编辑</el-button>
<el-button
type="text"
size="mini"
@click="handleSchedule('AddPeopleSchedule', scope.row.customer_id)"
>添加联系人</el-button>
</template>

<component
:is="currentComponent"
:customer_id="customer_id"
@componentResult="componentResult"
>
</component>

script中的代码:

这里的组件使用request按需引入,我使用的点击事件,当事件触发的时候,引入对应的组件

首先在data中声明组件的属性


data() {
return {
currentComponent: "",
customer_id:'',
}
}

然后注册组件

这里的组件作为一个个方法,组件名是方法名,组件内容是方法体,有几个组件就写几个方法


components: {
AddCustomerSchedule(resolve) {
require(["../components/AddCustomer"], resolve);
},
AddPeopleSchedule(resolve) {
require(["../components/AddPeople"], resolve);
},
CustomerInfoSchedule(resolve) {
require(["../components/CustomerInfo"], resolve);
},
VisitRecordSchedule(resolve) {
require(["../components/VisitRecord"], resolve);
},
},

定义的方法


// 这里直接接收name,然后相对应的引入组件,同时传值
handleSchedule(name, id) {
this.customer_id = id;
this.currentComponent = name;
},
// 这是子组件触发父组件返回回来的方法,因为我的组件都是弹出框
// 所以在子组件关闭弹出框的时候,我让this.currentComponent为空
// 同时可以选择性的刷新数据
componentResult(type) {
if (type == "upData") {
this.getTableData();
} else {
this.currentComponent = "";
}
},

总结