方法1:
buildMenuTree (menuList: Menu[], pid: string): MenuTree[] {
let result: MenuTree[] = [];
menuList.forEach(menu => {
const menuTree = new MenuTree();
menuTree.id = menu.id;
menuTree.name = menu.name;
menuTree.code = menu.code;
menuTree.route = menu.route;
if (menu.parentId === pid) {
menuTree.children = this.buildMenuTree(menuList, menu.id);
result.push(menuTree);
}
});
console.log(result);
return result;
}
方法2
buildMenuTree (menuList: Menu[], pid: string): MenuTree[] {
let result: MenuTree[] = [];
for (var i = 0; i < menuList.length; i++) {
if (menuList[i].parentId == pid) {
var menuTree: MenuTree = new MenuTree();
menuTree.id = menuList[i].id;
menuTree.name = menuList[i].name;
menuTree.code = menuList[i].code;
menuTree.route = menuList[i].route;
menuTree.children = this.buildMenuTree(menuList, menuList[i].id);
result.push(menuTree)
}
}
console.log(result);
return result;
}
查询调用
// 分页查询,带条件查询
async findPage (userQuery: MenuQuery): Promise<PageResult<any>> {
const queryBuilder = this.repository.createQueryBuilder('menu');
console.log(userQuery);
queryBuilder.where('user.deleted=0');
if (userQuery) {
let { pageIndex, pageSize } = userQuery;
if (pageIndex || pageIndex === 0) pageIndex = 1;
if (pageSize || pageSize === 0) pageSize = 10;
queryBuilder
.take(pageSize) //Sets maximal number of entities to take.
.skip(pageSize * (pageIndex - 1)); //Sets number of entities to skip.
}
if (userQuery.enabled) {
queryBuilder.where('menu.enabled=' + userQuery.enabled);
} else {
queryBuilder.where('menu.enabled=0');
}
const result = new PageResult<MenuTree>();
const [entities, total] = await queryBuilder.getManyAndCount();
const treeData: MenuTree[] = this.buildMenuTree(entities, '');
result.data = treeData;
result.total = total;
result.pageIndex = userQuery.pageIndex;
result.pageSize = userQuery.pageSize;
return result;
}
数据对象
export class MenuTree {
id: string;
name: string;
code: string;
route: string;
children: MenuTree[]
}
返回数据内容
{
"data": {
"data": [
{
"id": "0e3bd2dd-bce8-4f89-9b11-e2a92228f70b",
"name": "系统管理",
"code": "string",
"route": "/system",
"children": [
{
"id": "60d5e4dc-0d4b-4712-9df0-f0044d7d79df",
"name": "用户管理",
"code": "string",
"route": "/users",
"children": []
},
{
"id": "af5d069e-a7fc-4f95-b64e-a6aa5650c2c4",
"name": "菜单管理",
"code": "string",
"route": "/menus",
"children": []
}
]
},
{
"id": "ccd39ca0-5ac8-4e1f-bf61-a90317d47fbe",
"name": "商品管理",
"code": "shops",
"route": "/shops",
"children": [
{
"id": "3552d84f-4328-48d4-80ce-b5cd13826d79",
"name": "商品列表",
"code": "shops",
"route": "/shop",
"children": []
}
]
}
],
"total": 5,
"pageIndex": "1",
"pageSize": "10"
},
"code": 200,
"msg": "请求成功"
}