一、需求
- Ant Design of Vue官网中,第一次点击树节点会选中,再一次点击该树节点会取消选中,如图所示:
- 现有如下需求
- 根据左侧选中树节点,去请求接口获取右侧表格数据
- 第一次点击树节点则选中,再一次点击该树节点不会取消选中(不会取消高亮)
- 连续两次点击相同树节点不会发起二次请求
二、技术栈
- 前端框架:vue2
- 前端UI框架:Ant Design of Vue(v1.7.8)
三、思路
- 方法一:二次点击树节点时
selectedKeys
为空,直接 return
中断执行
- 方法二:手动设置选中的节点为当前点击的节点,这样每次点击都是一次选中
四、代码
<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,
treeSelectedKeys: '',
data: [],
columns,
};
},
methods: {
onSelect(selectedKeys, info) {
if (selectedKeys.length === 0) return
this.selectedKeys = selectedKeys
this.treeSelectedKeys = this.selectedKeys[0];
this.getList();
},
getList() {
axios
.post('https://www.fastmock.site/mock/api/ppg', {
key: this.treeSelectedKeys,
})
.then((res) => {
this.data = res.data;
});
},
},
};
</script>