Appearance
el-tree勾选会把上级节点的子节点全部勾选
方法一:根据情况设置check-strictly
在赋值 之前 设置 check-strictly = true,结束赋值后 设置 check-strictly = false
template:
html
<el-tree ref="treeFormRef" :data="treeData" :props="defaultProps" node-key="ID" :check-strictly="checkStrictly" show-checkbox @check-change="checkChange">
js
const checkStrictly = ref(false)
const setKeys = () => {
checkStrictly.value = true
// 赋值
const checkedKeys = []
checkedArr.forEach(x => checkedKeys.value.push(x.ID)) // 获得选中项的[...IDs]
treeFormRef.value.setCheckedKeys(checkedKeys)
// 赋值结束,将checkStrictly.value恢复为false
setTimeout(function () {
checkStrictly.value = false
}, 2000)
}
方法二:筛选出叶子节点作为checkedKeys
js
const setKeys = () => {
const checkedKeys = []
checkedArr.forEach(x => checkedKeys.value.push(x.ID)) // 获得选中项的[...IDs]
const arr = []
nextTick(() => {
checkedKeys.value.forEach(item => {
if (!treeFormRef.value.getNode(item).childNodes || !treeFormRef.value.getNode(item).childNodes.length) {
arr.push(item)
}
})
treeFormRef.value.setCheckedKeys(arr)
}
这里遍历所有checkedKeys,使用getNode(key).childNodes
判断是否叶子节点,是的就放入arr中,最后使用setCheckedKeys()
方法实现勾选。
这个方法一定要使用nextTick
,确保在树已经加载后调用getNode()