【Ant Design of Vue】Tree 树形控件双击树节点禁止取消选中(两种方法)

一、需求

  • Ant Design of Vue官网中,第一次点击树节点会选中,再一次点击该树节点会取消选中,如图所示:
    在这里插入图片描述
  • 现有如下需求
    • 根据左侧选中树节点,去请求接口获取右侧表格数据
    • 第一次点击树节点则选中,再一次点击该树节点不会取消选中(不会取消高亮)
    • 连续两次点击相同树节点不会发起二次请求
      在这里插入图片描述

二、技术栈

  • 前端框架:vue2
  • 前端UI框架:Ant Design of Vue(v1.7.8)

三、思路

  1. 方法一:二次点击树节点时 selectedKeys 为空,直接 return 中断执行
  2. 方法二:手动设置选中的节点为当前点击的节点,这样每次点击都是一次选中

四、代码

<template>
  <div style="display: flex">
    <a-tree defaultExpandAll :selected-keys="selectedKeys" :tree-data="treeData" @select="onSelect" />
    <a-table :columns="columns" :data-source="data" style="margin-left: 100px"></a-table>
  </div>
</template>

<script>
import axios from 'axios';
const treeData = [
  {
    title: '0-0',
    key: '0-0',
    children: [
      {
        title: '0-0-0',
        key: '0-0-0',
        children: [
          { title: '0-0-0-0', key: '0-0-0-0' },
          { title: '0-0-0-1', key: '0-0-0-1' },
          { title: '0-0-0-2', key: '0-0-0-2' },
        ],
      },
      {
        title: '0-0-2',
        key: '0-0-2',
      },
    ],
  },
  {
    title: '0-2',
    key: '0-2',
  },
];
const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
    width: 80,
  },
  {
    title: 'Address',
    dataIndex: 'address',
    key: 'address 1',
    width: 150,
    ellipsis: true,
  },
];
export default {
  data() {
    return {
      selectedKeys: [], // (受控)设置选中的树节点
      treeData, // treeNodes 数据
      treeSelectedKeys: '', // 接口请求中传递的树节点信息
      data: [], // 表格数据
      columns, // 表头信息
    };
  },
  methods: {
    onSelect(selectedKeys, info) {
      // 方法一: 二次点击树节点时selectedKeys为空,直接return中断执行
      if (selectedKeys.length === 0) return
      this.selectedKeys = selectedKeys
      this.treeSelectedKeys = this.selectedKeys[0];
      
      // 方法二:手动设置选中的节点为当前点击的节点,这样每次点击都是一次选中
      // const { key } = info.node.dataRef;
      // this.selectedKeys = [key];
      // if (this.treeSelectedKeys === this.selectedKeys[0]) return;
      // this.treeSelectedKeys = this.selectedKeys[0];
      
      this.getList();
    },
    getList() {
      // 接口请求,这里使用fastmock模拟数据
      axios
        .post('https://www.fastmock.site/mock/api/ppg', {
          key: this.treeSelectedKeys,
        })
        .then((res) => {
          this.data = res.data;
        });
    },
  },
};
</script>
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值