本文最后更新于 2024-10-17T11:18:40+08:00
template
1 2 3 4 5
| <a-ascader v-model:value="value" :options="options" :load-data="loadData" change-on-select />
|
script
动态加载数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const options = ref([]); const value = rf("");
const loadQylbData = (selectedOptions) => { const targetOption = selectedOptions[selectedOptions.length - 1]; targetOption.loading = true;
fetchData({ pid: targetOption.id }).then((res) => { if (res.length) { targetOption.loading = false; targetOption.children = res.map((item) => { return { ...item, children: [], isLeaf: false }; }); options.value = [...options.value]; } else { targetOption.isLeaf = true; options.value = [...options.value]; } }); };
|
编辑回显
1 2 3 4 5 6 7 8 9 10 11
| const promisesArr = value.value.map((id) => fetchData({ pid: id }));
Promise.all(promises) .then((results) => { options.value = list2tree([].concat(...results)); }) .catch((error) => { console.error(error); });
|
将数组转为 tree 结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| function list2tree( data: any[], id = "id", parentId = "pid", children = "children" ) { const map: any = {}; const tree: any = []; data.forEach((item: any) => { map[item[id]] = item; });
data.forEach((item: any) => { const parent = map[item[parentId]];
if (parent) { (parent[children] || (parent[children] = [])).push(item); } else { tree.push(item); } });
return tree; }
|
a-cascader动态加载数据和编辑回显
https://mengluo.com/2024/08/21/a-cascader动态加载数据和编辑回显/