持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情
前提:公司旧系统更新某个功能,后台那边规定了如哦选中子节点的话,那么请求接口需要连同父节点一起传入
解决:首先原本已经使用了getCheckedKeys()去获取目前被选中的节点的 key 所组成的数组,现在需要获取父节点,这是发现el-tree还有一个方法getHalfCheckedKeys可以获取半选中的节点的 key 所组成的数组
如图,红色框住的就是我们希望也能获取到的父节点(这里就是半选中的节点),绿色框就是常用来获取选中的节点数据
案例代码如下:
<template>
<div>
<el-tree :data="data" show-checkbox default-expand-all node-key="id"
ref="tree" highlight-current :props="defaultProps">
</el-tree>
<div class="buttons">
<el-button @click="getCheckedKeys">通过选中以及半选中的数组</el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
data: [
{
id: 1,
label: "一级 1",
children: [
{
id: 4,
label: "二级 1-1",
children: [
{
id: 9,
label: "三级 1-1-1",
},
{
id: 10,
label: "三级 1-1-2",
},
],
},
],
},
{
id: 2,
label: "一级 2",
children: [
{
id: 5,
label: "二级 2-1",
},
{
id: 6,
label: "二级 2-2",
},
],
},
{
id: 3,
label: "一级 3",
children: [
{
id: 7,
label: "二级 3-1",
},
{
id: 8,
label: "二级 3-2",
},
],
},
],
defaultProps: {
children: "children",
label: "label",
},
};
},
methods: {
getCheckedKeys() {
// 获取选中节点的数组
const checkedKey = this.$refs.tree.getCheckedKeys();
// 获取半选中系节点的数组
const halfCheckedKey = this.$refs.tree.getHalfCheckedKeys();
console.log("获取选中节点的数组", checkedKey);
console.log("获取半选中系节点的数组", halfCheckedKey);
console.log("选中+半选中的数据", checkedKey.concat(halfCheckedKey));
},
},
};
</script>