<el-tree
ref="tree"
lazy
:data="menus"
:default-checked-keys="checkedKeys"
:load="getDatas"
check-strictly
show-checkbox
node-key="id"
@check="checkChange"
/>
- 默认选中节点
getChecked(val) {
this.$refs.tree.setCheckedKeys([])
// 初始化默认选中的key
this.checkedKeys= []
val.forEach(function(data) {
this.checkedKeys.push(data.id)
})
this.$refs.tree.setCheckedKeys(this.checkedKeys) // 赋值选中
}
- 节点选中状态改变
async checkChange(node) {
// 获取子节点,包含自己
const childResp = await getChild(node.id)
if (this.checkedKeys.indexOf(node.id) !== -1) {
// 子节点
for (let i = 0; i < childResp.data.length; i++) {
const index = this.checkedKeys.indexOf(childResp.data[i])
if (index !== -1) {
this.checkedKeys.splice(index, 1)
}
}
// 判断是否有父节点
if (node.parentId !== 0) {
const resp = await getChildsTree({ pid: node.parentId })
const arr = [...this.checkedKeys.values()].filter(el => [...resp.data].some(i => i.id === el))
if (arr.length === 0) {
const ind = this.checkedKeys.indexOf(node.parentId)
if (ind !== -1) {
this.checkedKeys.splice(ind, 1)
}
}
}
} else {
// 子节点
for (let i = 0; i < childResp.data.length; i++) {
const index = this.checkedKeys.indexOf(childResp.data[i])
if (index === -1) {
this.checkedKeys.push(childResp.data[i])
}
}
// 父节点
if (node.parentId !== 0) {
const pNode = this.$refs.tree.getNode(node.parentId)
pNode.indeterminate = true
this.checkedKeys.push(node.parentId)
}
}
this.$refs.tree.setCheckedKeys(this.checkedKeys)
}
不足之处还望指正!