You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ant-design-vue/components/table/demo/ajax.vue

120 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<docs>
---
order: 10
title:
en-US: Ajax
zh-CN: 远程加载数据
---
## zh-CN
这个例子通过简单的 ajax 读取方式演示了如何从服务端读取并展现数据具有筛选排序等功能以及页面 loading 效果开发者可以自行接入其他数据处理方式
另外本例也展示了筛选排序功能如何交给服务端实现列不需要指定具体的 `onFilter` `sorter` 函数而是在把筛选和排序的参数发到服务端来处理
当使用 `rowSelection` 请设置 `rowSelection.preserveSelectedRowKeys` 属性以保留 `key`
## en-US
This example shows how to fetch and present data from a remote server, and how to implement filtering and sorting in server side by sending related parameters to server.
Setting `rowSelection.preserveSelectedRowKeys` to keep the `key` when enable selection.
**Note, this example use [Mock API](https://randomuser.me) that you can look up in Network Console.**
</docs>
<template>
<a-table
:columns="columns"
:row-key="record => record.login.uuid"
:data-source="dataSource"
:pagination="pagination"
:loading="loading"
@change="handleTableChange"
>
<template #bodyCell="{ column, text }">
<template v-if="column.dataIndex === 'name'">{{ text.first }} {{ text.last }}</template>
</template>
</a-table>
</template>
<script lang="ts" setup>
import { computed } from 'vue';
import type { TableProps } from 'ant-design-vue';
import { usePagination } from 'vue-request';
import axios from 'axios';
const columns = [
{
title: 'Name',
dataIndex: 'name',
sorter: true,
width: '20%',
},
{
title: 'Gender',
dataIndex: 'gender',
filters: [
{ text: 'Male', value: 'male' },
{ text: 'Female', value: 'female' },
],
width: '20%',
},
{
title: 'Email',
dataIndex: 'email',
},
];
type APIParams = {
results: number;
page?: number;
sortField?: string;
sortOrder?: number;
[key: string]: any;
};
type APIResult = {
results: {
gender: 'female' | 'male';
name: string;
email: string;
}[];
};
const queryData = (params: APIParams) => {
return axios.get<APIResult>('https://randomuser.me/api?noinfo', { params });
};
const {
data: dataSource,
run,
loading,
current,
pageSize,
} = usePagination(queryData, {
formatResult: res => res.data.results,
pagination: {
currentKey: 'page',
pageSizeKey: 'results',
},
});
const pagination = computed(() => ({
total: 200,
current: current.value,
pageSize: pageSize.value,
}));
const handleTableChange: TableProps['onChange'] = (
pag: { pageSize: number; current: number },
filters: any,
sorter: any,
) => {
run({
results: pag.pageSize,
page: pag?.current,
sortField: sorter.field,
sortOrder: sorter.order,
...filters,
});
};
</script>