AntDesign-Vue Table 查詢與分頁
前言
之前的增刪改查小 Demo 已經快要進行到最后一步了,這節的任務是將請求數據的方式改為 分頁,并且增加 分頁條件查詢 的功能。
頁面布局
<a-table
:data-source="dataSource"
:columns="columns"
:pagination="pagination"
>
<!-- ↑ pagination 是分頁功能,傳入一個對象 -->
<!-- ↓ 為 a-table 組件添加個表頭,里面有一個輸入框和一個按鈕 -->
<template #title>
<div>
<div>
<!-- 為輸入框綁定事件 -->
<a-input :bordered="false" placeholder="請輸入水果名稱" @keydown.enter="fnc_search" id="search">
</a-input>
<!-- 為按鈕綁定事件 -->
<a-button @click="fnc_search">
<!-- ↓ 一個放大鏡按鈕 -->
<SearchOutlined></SearchOutlined>
</a-button>
</div>
<!-- 在表格中添加數據的按鈕,和這篇文章沒關系 -->
<a-button @click="showAddModal">添加</a-button>
</div>
</template>
<!-- ↓ 顯示圖片的 template -->
<template v-slot:bodyCell="{ column, record, index}">
<template v-if="column.dataIndex === 'pic'">
<img :src="record.avatar" @click="checkInfo(record, index)"/>
</template>
</template>
</a-table>

邏輯部分
const keywords = ref("");
// ↑ 用以儲存查詢關鍵詞的變量
// ↓ 分頁對象
const pagination = reactive({
defaultPageSize: 8, // 默認每頁顯示多少個
defaultCurrent: 1,
total: 0,
current: 1,
onChange: (current: number, size: number) => {
console.log("改變了頁數");
console.log("current: ", current);
console.log("size: ", size);
pagination.current = current;
getFruitsRequest(keywords.value, current, dataSource, pagination);
// getFruitsRequest 函數在 api.js 這個文件里,下面會提到
}
})
// 在掛載頁面時請求數據,此時 keywords 為空字符串
onMounted(() => {
getFruitsRequest(keywords.value, 1, dataSource, pagination);
})
// ↓ 表格列數據
const columns = [
{
title: '水果名稱',
dataIndex: 'fruitName',
key: 'fruitName',
},
{
title: '圖片',
dataIndex: 'pic',
key: 'pic',
},
{
title: '價格 (元/公斤)',
dataIndex: 'price',
key: 'price',
},
{
title: '庫存(公斤)',
dataIndex: 'stock',
key: 'stock',
},
];
/**
* 點擊搜索按鈕的回調
*/
function fnc_search() {
// 輸入框 id 為 search
// 這里通過 js 拿到 a-input 內的數據
// 如果使用 v-model 方式的話會在輸入框內數據發生改變時就改變 keyword 的值
// 導致在輸入框中有內容時,沒有點擊搜索按鈕而直接點擊翻頁按鈕也會觸發關鍵詞搜索
if ((document.getElementById("search") as any).value === "") {
// ↓ 如果值為空則將 keywords 置空
keywords.value = "";
} else {
// ↓ 前面加一個 '/' 為了拼接 api 接口
// 例如:
// http://www.xx00.com/fruits/1/5
// ↑ 請求分頁,第一頁,請求五條數據
// http://www.xx00.com/fruits/apple/2/3
// ↑ 請求分頁,關鍵詞:apple,第二頁,請求三條數據
keywords.value = '/' + (document.getElementById("search") as any).value;
}
getFruitsRequest(keywords.value, 1, dataSource, pagination);
// ↓ 點擊搜索后,將當前頁數置為1
pagination.current = 1;
}
// api.ts
import axios from "axios";
const fruitApi = axios.create({
// 設置超出響應時間
timeout: 5000
})
/**
* 分頁查詢
*/
export function getFruitsRequest(keywords = "", currentPage: number, dataSource: any, pagination: any) {
fruitApi({
method: 'get',
url: 'api/fruits' + keywords + '/' + currentPage + '/8'
// 默認請求 8 條數據
})
.then((resp) => {
console.log(resp.data);
// ↓ 分頁查詢需要 .records
dataSource.value = resp.data.records;
// ↑ 查詢完成后替換數據源
pagination.total = resp.data.total;
// ↑ 改變數據總數
})
.catch((e) => {
console.log("e: ", e);
})
}
測試




浙公網安備 33010602011771號