1. 数据渲染
template部分:
<a-cascader
v-model:value="selected"
:options="options"
:load-data="loadData"
placeholder="请选择"
/>
js部分:
const options = ref<any>([])
const getList = async (cat_id: string | number) => {
let res = await cateListApi({ id })
if (res.code === 0) {
res.cont.forEach((item: any) => {
options.value.push({
label: item.name,
value: item.id,
isLeaf: item.isLeaf,
})
})
return options.value
}
}
onMounted(() => {
getList(0)
})
const loadData = (selectedOptions: Option[]) => {
const targetOption = selectedOptions[selectedOptions.length - 1];
targetOption.loading = true;
setTimeout(async () => {
targetOption.loading = false;
let res = await cateListApi({ id: targetOption.value })
if (res.code === 0) {
targetOption.children = res.cont.map((item: any) => {
return {
label: item.name,
value: item.id,
isLeaf: item.isLeaf,
}
})
options.value = [...options.value];
}
}, 500);
};
2. 数据回显
比如接口返回数据为selected=[1, 11, 111] // 表示选择了第一个的三级数据
onMounted(() => {
getParentNodes(selected, list.value)
})
const getParentNodes = async (ids: [], tree: []) => {
for (let i = 0; i < ids.length - 1; i++) {
tree.forEach(async (item: any) => {
if (item.value === ids[i]) {
item.children = []
let data = []
data = await cateListApi({ id: ids[i] })
item.children = data.cont.map((child: any) => {
return {
label: child.catName,
value: child.catId,
isLeaf: child.isLeaf
}
})
getParentNodes(ids, item.children)
}
})
}
}