具体的な効果とコードは次のとおりです。
「ノード 1」をクリックして強調表示した
:highlight-current="true"
印刷結果は以下の通りです
vue3 の印刷オブジェクトは proxy なので、単純な配列オブジェクトに変換する必要がある場合は、JSON.parse(JSON.stringify(list)) を使用して変換できます。
現在の選択をキャンセルするには、「ノード 1」を再度クリックします。
完全なコードを投稿します。
<template>
<el-tree
:data="treeData"
:props="defaultProps"
:expand-on-click-node="false"
@node-click="handleNodeClick"
:highlight-current="true"
:current-node-key="selectedNodeId"
/>
</template>
<script lang="ts">
import { defineComponent,ref,reactive,toRefs ,onMounted} from 'vue'
import { ElTree } from 'element-plus';
export default defineComponent({
name: 'SelectTree',
components: {
ElTree,
},
setup() {
// 树形结构数据
const treeData = ref([
{
id: 1,
label: '节点1',
children: [
{ id: 2, label: '节点1-1' },
{ id: 3, label: '节点1-2' },
],
},
{ id: 4, label: '节点2' },
{ id: 5, label: '节点3' },
]);
// 默认 props 配置项
const defaultProps = {
children: 'children',
label: 'label',
};
// 当前选中的节点 id
const selectedNodeId = ref(null as any);//做类型断言处理
// 处理节点点击事件
function handleNodeClick(data: any) {
console.log(data)
if (data.id === selectedNodeId.value) {
// 如果当前节点已经选中,则取消选中
selectedNodeId.value = null;
console.log( selectedNodeId.value,"取消选中")
} else {
// 否则选中当前节点
selectedNodeId.value = data.id;
console.log( selectedNodeId.value,"当前选中的节点")
}
}
onMounted(()=>{
// 在这可以设置默认选中的节点
// selectedNodeId.value = 1
})
return {
treeData,
defaultProps,
selectedNodeId,
handleNodeClick,
};
},
});
</script>
<style scoped lang="scss">
</style>
役に立った場合は、「いいね」を押し、フォローして保存してください。