Andv树组件获取当前选中的节点

问题

Antdv 中树形组件的select事件的两个参数分别为selectedKeyse,获取当前选中的节点的方法:

  1. 通过事件的e.node.dataRef获取
  2. 通过selectedKey获取
<a-tree
  :tree-data="trees"
  :replace-fields="{title: 'name', key: 'id'}"
  :show-line="true"
  @select="onSelect"
/>

第二种方案如果以记录的idkey就不得不对树结构进行展开或者递归。解决方案为:在组装树的时候生成路径来作为key

解决

路径ID数组转JSON工具方法(需配置Jackson将Long序列化String):

private String pathIdsToJsonArray(List<Long> pathIds) {
    String pathIdJsonArray;
    try {
        pathIdJsonArray = objectMapper.writeValueAsString(pathIds);
    } catch (JsonProcessingException e) {
        pathIdJsonArray = "";
    }
    return pathIdJsonArray;
}

组装成树:

public List<Category> getCategoryTreeList() {
    List<Category> nodes = super.list();
    return nodes.stream()
        .filter(node -> node.getParentId() == 0)
        .peek(node -> {
            List<Long> pathIds = new ArrayList<>();
            // 一级分类只添加自身ID
            pathIds.add(node.getId());
            String pathIdJsonArray = this.pathIdsToJsonArray(pathIds);
            node.setPathIdJsonArray(pathIdJsonArray);
            this.combineToTree(node, pathIds, nodes);
        })
        .collect(Collectors.toList());
}

private void combineToTree(Category root, List<Long> rootPathIds, List<Category> nodes) {
    List<Category> children = nodes.stream()
        .filter(node -> node.getParentId().equals(root.getId()))
        .peek(node -> {
            // 非一级分类先添加父分类的路径数组再添加自身ID
            List<Long> pathIds = new ArrayList<>(rootPathIds);
            pathIds.add(node.getId());
            String pathIdJsonArray = this.pathIdsToJsonArray(pathIds);
            node.setPathIdJsonArray(pathIdJsonArray);
            this.combineToTree(node, pathIds, nodes);
        })
        .collect(Collectors.toList());
    root.setChildren(children);
}

组件(单选):

<template>
  <a-tree
    :tree-data="trees"
    :replace-fields="{title: 'name', key: 'pathIdJsonArray'}"
    :show-line="true"
    @select="onSelect"
  />
</template>

<script>
export default {
  props: {
    trees: { type: Array, default: () => [] }
  },
  methods: {
    onSelect ([pathIdJsonArray1]) {
      // [一级分类ID, 二级分类ID, ...剩余分类ID]
      const pathIds = JSON.parse(pathIdJsonArray1)
      let target = { children: this.trees }
      for (let i = 0; i < pathIds.length; i++) {
        target = target.children.find(item => item.id === pathIds[i])
      }
      this.$emit('selectedNode', target)
    }
  }
}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值