有问题的代码
<template>
<div class="flex h-full ml-10px">
<BasicTree
title="公司列表"
toolbar
search
treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
:clickRowToExpand="false"
:treeData="treeData"
:fieldNames="{ key: 'id', title: 'text' }"
@select="handleSelectTree"
/>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, onMounted, unref } from 'vue';
import { BasicTree} from '/@/components/Tree';
export default defineComponent({
components: { BasicTree},
setup(){
const treeData = ref([]);
const treeRef = ref(null);
function getTree() {
const tree = unref(treeRef);
if (!tree) {
throw new Error('tree is null!');
}
return tree;
}
function handleSelectTree() {
const keys = getTree().getSelectedKeys();
const node = getTree().getSelectedNode(keys[0]);
console.log('node',node) // 输出null
}
const treeData = [
{
id: '1',
text: '一级菜单',
}
];
return {
treeRef,
treeData,
handleSelectTree,
};
},
})
</script>
查看了getSelectedNode方法才发现这个key是固定写死的,并没有从fieldNames里取值,所以一直输出null。
解决办法:修改下getSelectedNode函数,动态获取key;