解決的問題:
1、 當拿到了后台的數據,使用id去渲染選中的節點時,如果父級id包含在id數組里,而此id下面的子節點只有部分選中的情況下,此父級id下面得所有子節點全部被選中了。
2、 當需要保存當前選中的節點id時,拿不到半選中的父級id。
<el-tree
ref="tree"
v-loading="loading"
:data="data"
:props="defaultProps"
:show-checkbox="showCheckBox" // 展示復選框
node-key="id" // 如果需要通過 key 來獲取或設置,則必須設置node-key 即可以設置為id
@node-expand="handleNodeExpand"
@check-change="handleCheckChange"
/>
data: [{
id: 1,
label: '一級 1',
select: true,
children: [{
id: 4,
label: '二級 1-1',
select: false,
children: [{
id: 9,
label: '三級 1-1-1',
select: false
}, {
id: 10,
label: '三級 1-1-2',
select: true
}]
}]
}, {
id: 2,
label: '一級 2',
select: true,
children: [{
id: 5,
label: '二級 2-1',
select: false
}, {
id: 6,
label: '二級 2-2',
select: false
}]
}, {
id: 3,
label: '一級 3',
select: true,
children: [{
id: 7,
label: '二級 3-1',
select: true
}, {
id: 8,
label: '二級 3-2',
select: false
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
data為后台拿到的數據結構 select為判斷這個節點是否為選中的狀態,通過遞歸的方式將所有選中的數據的id放在數組this.checkedKeys里面
getSelectKey(list) {
this.data.map((ele, index) => {
if (ele.select) {
this.checkedKeys.push(ele.id)
}
if (ele.childs.length > 0) {
this.getSelectKey(ele.children)
}
})
},
拿到所有選中的id之后
checkedKeys(val) {
this.$refs.tree.setCheckedKeys([]) // 先清空選中
this.$nextTick(() => {
const that = this
val.forEach((i, n) => {
const node = that.$refs.tree.getNode(i)
if (node.isLeaf) {
that.$refs.tree.setChecked(node, true)
}
})
})
}
這樣就將選中的數據渲染出來了
基本上能拿到類似這樣的效果,上面的數據是亂寫的 這里只做展示效果
最后想要拿到最后選中的數據的集合
handleCheckChange() { // tree勾選的方法
// 勾選的key
const checkedKeys = this.$refs.tree.getCheckedKeys()
// 暫選狀態的母tab的key
const halfKeys = this.$refs.tree.getHalfCheckedKeys()
// 合並兩個數組
const save = checkedKeys.concat(halfKeys)
this.$emit('allSelectedKeys', save)
},
這樣就能夠拿到半勾選的父級的id的此id下面選中的數據的id了