【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>

猜你喜欢

转载自blog.csdn.net/weixin_43417844/article/details/130007863