实例:实现Ant Design Vue的级联选择
层级数据:有父子关系的数组,且子节点都会放到该节点的children下。
<a-cascader
:options="options"
/>
data() {
return {
options: [],
};
},
created() {
this.getData();
},
methods: {
getData() {
const data = [
{
"id":"60404a146fe3ff06ff74e06b",
"name":"Test 22",
"parentId":"",
},
{
"id":"60404a006fe3ff06fb4436c6",
"name":"Test 11",
"parentId":"",
},
{
"id":"604045f6b2fc301fde55f8c2",
"name":"Test 4",
"parentId":"604045dfb2fc30196037f916",
},
{
"id":"604045f4b2fc301fb804d3d3",
"name":"三级分类1-3-2",
"parentId":"604045e0b2fc30191e192645",
},
{
"id":"604045f1b2fc301fa207d323",
"name":"三级分类1-3-1",
"parentId":"604045e0b2fc30191e192645",
},
{
"id":"604045e0b2fc30191e192645",
"name":"二级分类1-3",
"parentId":"6040459bb2fc3019011a8ee5",
},
{
"id":"604045dfb2fc30196037f916",
"name":"Test 3",
"parentId":"604045cfb2fc30190862523b",
},
{
"id":"604045dcb2fc3018fc2569a7",
"name":"二级分类1-2",
"parentId":"6040459bb2fc3019011a8ee5",
},
{
"id":"604045d7b2fc3019364c2dd5",
"name":"二级分类1-1",
"parentId":"6040459bb2fc3019011a8ee5",
},
{
"id":"604045cfb2fc30190862523b",
"name":"Test 2",
"parentId":"604045bfb2fc30196037f915",
},
{
"id":"604045bfb2fc30196037f915",
"name":"Cynthia Test",
"parentId":"",
},
{
"id":"604045a5b2fc301908625236",
"name":"一级分类3",
"parentId":"",
},
{
"id":"604045a0b2fc30191d3cd524",
"name":"一级分类2",
"parentId":"",
},
{
"id":"6040459bb2fc3019011a8ee5",
"name":"一级分类1",
"parentId":"",
}
];
data.forEach((item) => {
const { id, name } = item;
item.value = id;
item.label = name;
});
this.classificationOptions = this.treeData(data);
},
treeData(data) {
const cloneData = JSON.parse(JSON.stringify(data));
return cloneData.filter((father) => {
const branchArr = cloneData.filter((child) => father.id === child.parentId);
if (branchArr.length > 0) {
father.children = branchArr;
}
return father.parentId === ''; //返回第一层
});
},
},