1. 设置默认选中:
使用 default-checked-keys 属性,设置默认要选中的节点,以数组形式,如下:
<el-tree
ref="treeRef"
:data="data"
show-checkbox
node-key="id"
:props="defaultProps"
:default-checked-keys="[5]"
/>
2. 调用 Tree 实例对象的 getCheckedKeys 方法来获取选中的所有节点,如下:
const treeRef = ref();
const checkedId = ref([]);
function getCheckedId() {
checkedId.value = treeRef.value?.getCheckedKeys();
}
完整代码如下:
<template>
<div>
<el-tree
ref="treeRef"
:data="data"
show-checkbox
node-key="id"
:props="defaultProps"
:default-checked-keys="[5]"
/>
<el-button @click="getCheckedId">获取选中节点: {{ checkedId }}</el-button>
</div>
</template>
<script setup>
const defaultProps = {
children: "children",
label: "label",
};
const data = [
{
id: 1,
label: "Level one 1",
children: [
{
id: 2,
label: "Level two 1-1",
children: [
{
id: 3,
label: "Level three 1-1-1",
},
{
id: 4,
label: "Level three 1-1-2",
},
],
},
],
},
{
id: 5,
label: "Level two 1",
},
];
const treeRef = ref();
const checkedId = ref([]);
function getCheckedId() {
checkedId.value = treeRef.value?.getCheckedKeys();
}
</script>