背景:
記錄el-cascader多選+懶加載+數據回顯的實際案例。
注意:
1.回顯數據的時候除了給v-model
綁定的屬性賦值以外,還要提供一個包含需要渲染的級聯數據的options模板。
2.resolve(nodes) 返回的nodes為下一級要渲染的list列表數據,如果是回顯已提供了options渲染模板但是不完整,則需要在后面懶加載的時候將返回的list數據和已存在的節點數據做對比,僅保留options中不存在的節點數據再把過濾后的節點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: {
//回顯數據的模板
options: [{
"children": [{
"children": [{
"label": "infra-test-01",
"value": "infra-test-01"
}],
"label": "usne",
"value": "usne"
}],
"label": "AZURE-CLOUD",
"value": "3"
}],
//需要回顯的三級數據
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) { //點擊城市level=2加載vpc列表
this.getCloudInfo(node, resolve, node.parent.value, node.value)
} else if(level === 1) { //點擊云服務level=1加載城市列表
this.getCloudInfo(node, resolve, node.value)
} else { //初始化level=0加載云服務列表
this.getCloudInfo(node, resolve)
}
}
},
},
watch: {
// 監聽環境變化
'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) {
//切換環境重置云服務列表 通過v-if觸發三級聯動自動加載
this.formData.vpc_info = []
this.cascaderVisible = false
this.$nextTick(() => {
this.cascaderVisible = true
})
}
}
},
},
methods: {
// 懶加載獲取三級聯動數據
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) {
//將當前節點已有的子節點和重新請求的node節點對比,如已存在則移除該節點再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>