程序调用自身的编程技巧称为递归( recursion)。
递归 粗略的理解为 循环 ,只不过 递归 是调用自身。
在实际使用中,需要给递归设置一个边界条件,用该边界条件来判断是否继续递归下去。
如果不设置判断条件,将会导致 无限递归 ,也就是 死循环!
提示:以下是本篇文章正文内容,下面案例可供参考
直接在setup定义该数组
//数据随便写的,不符合实际情况,因为懒得改
const cityList = [
{name: "金水区", value: "111",id:'1',pid:null},
{name: "管城区", value: "222",id:'1-2',pid:'1'},
{name: "惠济区", value: "458",id:'2',pid:null},
{name: "二七区", value: "445",id:'2-1',pid:'2'},
{name: "新郑市", value: "456",id:'2-2',pid:'2'},
{name: "荥阳市", value: "647",id:'2-3',pid:'2'},
{name: "巩义市", value: "189",id:'3',pid:null},
{name: "经开区", value: "664",id:'3-1',pid:'3'},
{name: "郑东区", value: "652",id:'3-2',pid:'3'},
{name: "航空港区", value: "732",id:'3-3',pid:'3'},
{name: "郑州市", value: "852",id:'3-3-1',pid:'3-3'},
];
直接在setup定义该函数,然后onMounted钩子自动调用或根据需要手动调用该函数
function getMenuTree(menuList, pid) {
let treeList = [];
for (let i = 0; i < menuList.length; i++) {
let menu = menuList[i];
if (menu.pid === pid) {
let tree = {
id: menu.id,
name: menu.name,
children: getMenuTree(menuList, menu.id)
};
tree.children.length === 0 && delete tree.children;
treeList.push(tree);
}
}
return treeList;
}