背景:
記錄el-cascader多選+懶加載+數(shù)據(jù)回顯的實(shí)際案例。
注意:
1.回顯數(shù)據(jù)的時(shí)候除了給v-model
綁定的屬性賦值以外姿现,還要提供一個(gè)包含需要渲染的級(jí)聯(lián)數(shù)據(jù)的options模板竿痰。
2.resolve(nodes) 返回的nodes為下一級(jí)要渲染的list列表數(shù)據(jù)苟弛,如果是回顯已提供了options渲染模板但是不完整,則需要在后面懶加載的時(shí)候?qū)⒎祷氐膌ist數(shù)據(jù)和已存在的節(jié)點(diǎn)數(shù)據(jù)做對(duì)比,僅保留options中不存在的節(jié)點(diǎn)數(shù)據(jù)再把過濾后的節(jié)點(diǎn)resolve(nodes)潦刃。
<template>
<div>
<!--template模板中引用-->
<el-cascader style="width: 100%" :props="cascaderProps" :options="formData.options" v-model="formData.vpc_info" @change="cascaderChange" v-if="cascaderVisible">
</div>
</template>
<script>
export default {
data() {
formData: {
//回顯數(shù)據(jù)的模板
options: [{
"children": [{
"children": [{
"label": "infra-test-01",
"value": "infra-test-01"
}],
"label": "usne",
"value": "usne"
}],
"label": "AZURE-CLOUD",
"value": "3"
}],
//需要回顯的三級(jí)數(shù)據(jù)
vpc_info: [
['3', 'usne', 'infra-test-01']
],
},
cascaderVisible: true,
cascaderProps: {
lazy: true,
multiple: true,
lazyLoad: (node, resolve) => {
const {
level
} = node;
console.log('lazyLoadnode', node)
if(level === 2) { //點(diǎn)擊城市l(wèi)evel=2加載vpc列表
this.getCloudInfo(node, resolve, node.parent.value, node.value)
} else if(level === 1) { //點(diǎn)擊云服務(wù)level=1加載城市列表
this.getCloudInfo(node, resolve, node.value)
} else { //初始化level=0加載云服務(wù)列表
this.getCloudInfo(node, resolve)
}
}
},
},
watch: {
// 監(jiān)聽環(huán)境變化
'formData.cd_work_env': {
handler(cd_work_env, value) {
console.log('cd_work_env改變---', cd_work_env)
if(cd_work_env && cd_work_env !== value) {
//切換環(huán)境重置云服務(wù)列表 通過v-if觸發(fā)三級(jí)聯(lián)動(dòng)自動(dòng)加載
this.formData.vpc_info = []
this.cascaderVisible = false
this.$nextTick(() => {
this.cascaderVisible = true
})
}
}
},
},
methods: {
// 懶加載獲取三級(jí)聯(lián)動(dòng)數(shù)據(jù)
getCloudInfo(node, resolve, cloudId = '', areaId = '') {
if(!this.formData.cd_work_env) {
return false;
}
_fetch({
url: '/deploy-resource-management/mixCloud/getCloudInfoBySytemId',
type: 'post',
data: {
system_id: this.formData.cd_work_system,
env: this.formData.cd_work_env,
cloud_type: cloudId,
area: areaId,
}
}).then(res => {
if(res.data.code === 200) {
//將當(dāng)前節(jié)點(diǎn)已有的子節(jié)點(diǎn)和重新請(qǐng)求的node節(jié)點(diǎn)對(duì)比侮措,如已存在則移除該節(jié)點(diǎn)再resolve
if(res.data.body.type && res.data.body.type.length) {
let nodes = res.data.body.type.map(item => {
return { ...item,
leaf: node.level >= 2
}
})
if(node.hasChildren && node.children.length) {
let list = []
node.children.forEach(item => {
let flag = true
nodes.forEach(subItem => {
if(item.value === subItem.value) {
flag = false
}
})
if(flag) {
list.push(subItem)
}
})
resolve(list);
} else {
resolve(nodes);
}
} else {
resolve([]);
}
} else {
_message(this.$t("localization.common.error"), res.data.message, "error", this)
}
}).catch(err => {
console.log(err)
});
},
cascaderChange(value) {
console.log(value)
},
}
}
</script>