首先看看需求:
1,超级管理员,菜单默认全选,且不可点击,全部禁用
2,自定义角色,菜单默认清空选择,且全部可点击选择
首先解决全选和反选的问题,在切换权限的下拉框change事件里面进行判断:
// 权限change事件
// this.$refs.menuTree 是el-tree组件
// this.treeData 是el-tree的数据源
// this.currentRoleType 是当前的权限类别
changeCodeSort (info) {
if (this.currentRoleType == 3) { // 自定义角色---清空选择
this.checkedId = []
this.$nextTick(() => {
this.$refs.menuTree.setCheckedKeys(this.checkedId) // 设置选中项为空数组
})
} else if(this.currentRoleType == 2) { // 超级管理员---全选
this.$nextTick(() => {
this.$refs.menuTree.setCheckedNodes(this.treeData); // 这是利用el-tree的数据源设置全选
this.checkedId = this.$refs.menuTree.getCheckedKeys() // 光是设置全选只是视觉上的,还要再次获取一下已被选中节点的id数组,才能传给后端
})
}
},
然后解决全部禁用和取消禁用,首先官方组件有这样一个事件:check-change
:
就是在这个事件发生的时候,去判断禁用和取消禁用,设置禁用官方文档也有,就给每一个tree节点都设置disabled:true
,取消则是false
:
checkChnage (data,checked,checkedNodes) {
if(this.currentRoleType == 2) { // 超级--全部禁用
for(var i = 0; i < this.treeData.length; i++) { // 这个循环可以封装一下
var children = this.treeData[i].children
if (children != undefined) {
for(var g = 0; g< children.length; g++) {
children[g].disabled = true
}
}
this.treeData[i].disabled = true
}
} else { // 自定义--取消禁用
for(var i = 0; i < this.treeData.length; i++) { // 这个循环可以封装一下
var children = this.treeData[i].children
if (children != undefined) {
for(var g = 0; g< children.length; g++) {
children[g].disabled = false
}
}
this.treeData[i].disabled = false
}
}
},
至此已经实现了需求,但是要精益求精,然后又查了一下,这篇博文封装了一个map函数,写的挺简单的:
// 封装函数
const R = (f, s) => s.map(i => (
f(i), i.children && i.children != undefined ? R(f, i.children):0, i
))
// 在check-change时间里面调用:
checkChnage (data,checked,checkedNodes) {
if(this.currentRoleType == 2) { // 超级--全部禁用 // 用了一个_disabled作为中间属性
R(i => {
if (i._disabled===undefined) {
i._disabled = i.disabled===undefined ? false:i.disabled
}
i.disabled = true
}, this.treeData)
} else { // 自定义---取消禁用 // 用了一个_disabled作为中间属性
R(i => {
if (i._disabled!=undefined) {
i.disabled = i._disabled
delete i._disabled
}
}, this.treeData)
}
},
他这个封装函数拆开这样:
function G(i,bool) {
// 第一级
if (i._disabled === undefined) {
i._disabled = i.disabled === undefined ? false : i.disabled
}
i.disabled = bool
// 如果有子级
if (i.children && i.children != undefined) {
R(i.children,bool)
}
return i
}
var R = (s, bool) => {
return s.map(i => {
return G(i,bool)
})
}
// 调用
R(Data, true) / R(Data, false)
就酱~
苦海无涯,学习是岸~