使用el-cascader做多层级菜单,如果定义了最后一级不能做为父级(不能有子级)情况,则在级联菜单中,就不要显示最后一层子级菜单。可以通过再次查询数据库获取所需要的层级菜单,但是小编不想再查数据库,所以通过对数组过滤筛选出所要的数据。
1、未处理情况,显示了 ,上图:
2、变成两级
3、变成1级
4、代码,使用箭头函数写,不喜欢箭头函数往下看:
// 添加节点
append (data) {
this.dialogFormVisible = true
this.parentCategoryList = this.getTreeData(this.dataList, 2)
},
// 递归判断列表,把children设为undefined
// num 设定显示的层级
getTreeData (data, num) {
data.forEach(v => {
console.log(v)
if (v.catLevel <= num) {
if (v.catLevel === num) {
// children若为空数组,则将children设为undefined
v.children = undefined
} else {
// children若不为空数组,则继续 递归调用 本方法
this.getTreeData(v.children, num)
}
}
})
return data
}
5、非箭头函数写法:
// 递归判断列表,把最后层级的children设为undefined
// num 显示的层级
getTreeData (data, num) {
for (let i = 0; i < data.length; i++) {
if (data[i].catLevel <= num) {
if (data[i].catLevel === num) {
// children若为空数组,则将children设为undefined
data[i].children = undefined
} else {
// children若不为空数组,则继续 递归调用 本方法
this.getTreeData(data[i].children, num)
}
}
}
return data
},
6、点击编辑时,回显后台数据
// 添加节点, data为父点节数据
append (data) {
this.selectedKeys = []
this.dialogFormVisible = true
this.parentCategoryList = this.getTreeData(this.dataList, 2)
// 回显数据, selectedKeys 为 el-cascader 的 v-model 值
this.selectedKeys[0] = data.parentCid
this.selectedKeys[1] = data.catId
},