vue3+ant design vue动态实现级联菜单~
1、这里使用的是ant design vue 的TreeSelect 树选择来实现的。
<a-form-item name="staffDept" label="责任部门" labelAlign="left">
<a-tree-select
v-model:value="formState.staffDept"
show-search//允许在下拉框中添加搜索框
style="width: 100%"
:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"//设置下拉菜单的最大高度和溢出行为
placeholder="请输入"
allow-clear//显示清楚按钮
tree-default-expand-all//默认展开所有树节点
:tree-data="treeData"//将数据绑定在树形结构上
/>
</a-form-item>
import type { TreeSelectProps } from 'ant-design-vue';
import {getOrganizationChatrt} from '@/api/import';
const treeData = ref<TreeSelectProps['treeData']>([]);
const formState = ref({
staffDept: '',
});
const handData = (array, level?) => {
array.forEach((item, index) => {
if (level === 0) {//获取一级菜单
item.title = item.deptName;
item.value = item.deptId;
}
if (item.nodeOfChildren != null) {//获取二级菜单
item.children = [...item.nodeOfChildren];
item.children.map((res) => {
res.title = res.deptName;
res.value = res.deptId;
});
handData(item.nodeOfChildren);//递归遍历,获取后续菜单如三级菜单
}
});
treeData.value = array;
};
onMounted(() => {
getOrganizationChatrt({}).then((res) => {
console.log('测试数据', res);
handData(res, 0);
});
});
//假设这是后端返回的数据
[
{
"deptId": "00001",
"deptName": "营销中心",
"parentDeptId": "a00001",
"nodeOfChildren": [
{
"deptId": "000011",
"deptName": "网络管理部",
"parentDeptId": "00001",
"nodeOfChildren": [
{
"deptId": "0000111",
"deptName": "网络开发",
"parentDeptId": "000011",
"nodeOfChildren": null,
"title": "网络开发",
"value": "001"
},
{
"deptId": "0000112",
"deptName": "网络管理",
"parentDeptId": "000011",
"nodeOfChildren": null,
"title": "网络管理",
"value": "002"
}
]
},
{
"deptId": "000012",
"deptName": "市场营销部",
"parentDeptId": "00001",
"nodeOfChildren": null
}
]
}
]
2、效果图