vue3+ts implements the radio selection and cancellation functions of the element Plus Tree component (cancel the selected tree node), and the proxy object conversion of vue3

 The specific effects and code are as follows:

"Node 1" was clicked and highlighted

 :highlight-current="true"  

The print result is as follows

 The printing object of vue3 is proxy. If you need to convert it into a simple array object, you can use JSON.parse(JSON.stringify(list)) to convert it.

 Click "Node 1" again to cancel the current selection.

 

Post the complete code:
<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>

If it was helpful to you, give it a like, follow it and save it.

Guess you like

Origin blog.csdn.net/Timi_666/article/details/129947226