vue使用TreeSelect设置带所有父级节点的回显

在这里插入图片描述
Element Plus的el-tree-select组件

思路: 选中节点时,给选中的节点赋值 pathLabel,pathLabel 为函数生成的节点名字拼接,数据源中不包含。
在el-tree-select组件中设置 props=“{ label: ‘pathLabel’ }” 控制选中时input框中回显的字段。选择项的名称(option-label)使用插槽#default控制。

<template>
<div class="content">
  <el-tree-select filterable :data="deptData" :props="{ value: 'id', label: 'pathLabel', children: 'children' }"
    @change="handleDeptData" node-key="id"
    class="w100" clearable placeholder="请选择/输入分组"
    check-strictly :render-after-expand="true"
    v-model="deptIds">
    <template #default="{ data: { name } }">
      <span>{{ name }}</span>
    </template>
    </el-tree-select>
</div>
</template>
<script setup lang="ts">
const deptIds = ref('')
const deptData = ref([
  {
    id: 1100, name: '第一级', children: [
      { id: 1101, name: '1-1' ,children: [
          { id: 110101, name: '1-1-1' },
          { id: 110102, name: '1-2-2' },
          { id: 110103, name: '1-3-3' },
        ] },
      { id: 1102, name: '1-2' },
      { id: 1103, name: '1-3' },
    ]
  },
  {
    id: 1200, name: '第二级', children: [
      { id: 1201, name: '2-1' },
      { id: 1202, name: '2-2' },
      { id: 1203, name: '2-3' },
    ]
  },
])
const handleDeptData = (deptId: string) => {
  findPath(deptData.value, deptId);
}
  // 根据分组id获取分组名
function findPath(tree:any, targetId:string) {
  let path = [];
  let currentNode;
  // 查找节点
  function findNode(nodes, currentPath) {
    for (let node of nodes) {
      const newPath = [...currentPath, node.name];

      if (node.id === targetId) {
        currentNode = node;
        path = newPath;
        return true;
      }

      if (node.children && findNode(node.children, newPath)) {
        return true;
      }
    }
    return false;
  }
  findNode(tree, []);
  // 选中节点赋值 pathLabel
  if (currentNode) currentNode.pathLabel = path.length ? path.join('/') : null;
  return path.length ? path.join('/') : null;
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

echozzi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值