在使用element-ui级联选择器的过程中,发现出现 空级联 的bug
首先我们分析出现空级联原因是:由于数据是从后台传递过来的,当后端的老铁使用递归算出菜单,然后转换成json传递到前端的时候。就会出现 最底层 的子项中 的 children 为空数组,这样就会造成,空级联 的bug存在。
HTML部分
<el-cascader
:options="menuTree"
v-model="form.parentId"
:props="{ emitPath: false, expandTrigger: 'click',checkStrictly: true,value: 'id',label: 'name',children: 'childrens' }"
clearable>
</el-cascader>
JavaScript部分
// 获取级联选择器数据
getAllMenuTree () {
this.$api({
url: 'getAllMenuTree'
}).then(res => {
this.menuList = Object.assign([], res.data)
function clear (arr) {
arr.map(i => {
if (i.childrens.length === 0) {
delete i.childrens
} else {
clear(i.childrens)
}
})
}
// 调用递归方法,去除级联数据后将数据赋值给级联选择器
this.menuTree = this.getTreeData(res.data)
})
},
// 递归方法
getTreeData (data) {
// 循环遍历json数据
for (var i = 0; i < data.length; i++) {
if (data[i].childrens.length < 1) {
// children若为空数组,则将children设为undefined
data[i].childrens = undefined
} else {
// children若不为空数组,则继续 递归调用 本方法
this.getTreeData(data[i].childrens)
}
}
return data
}