公司做网站的价格南宁网站建设网络公司
在 Vue 中实现分页查询可以提升大型数据集的加载和显示效率。本文将逐步介绍如何使用 Vuex 状态管理和 axios HTTP 请求库来实现 Vue 分页查询。
1. 在 Vuex 中创建分页状态
首先,在 Vuex 状态管理中创建分页状态,该状态将存储每页的记录数、当前页码和正在加载数据的布尔值。例如:
const state = {currentPage: 1,pageSize: 10,isLoading: false,
}
2. 获取数据并更新状态
接下来,在组件的方法中使用 axios 向服务器发送 HTTP 请求以获取数据。在请求之前,将 isLoading 状态设置为 true,以在数据加载期间显示加载指示器。
async fetchRecords() {this.isLoading = true;const res = await axios.get(`/api/records?page=${this.currentPage}&size=${this.pageSize}`);this.records = res.data;this.isLoading = false;
}
3. 创建分页器组件
创建分页器组件来控制分页行为。该组件应提供导航按钮以在不同页面之间移动。
<template><nav><button>上页</button><button>下页</button></nav></template><script>
export default {methods: {prevPage() {if (this.currentPage > 1) this.currentPage--;},nextPage() {if (this.currentPage < this.totalPages) this.currentPage++;},},
}
</script>
4. 监听状态变化并重新获取数据
在组件中监听 currentPage 或 pageSize 状态变化,并在值发生变化时重新获取数据。
watch: {currentPage() {this.fetchRecords();},pageSize() {this.currentPage = 1;this.fetchRecords();},
}
5. 在视图中使用分页数据
最后,在视图中使用分页后的数据。例如,可以使用 v-for 指令来遍历记录并将其显示在表格中。
<div v-if="!isLoading"><table>
<thead><tr>
<th>ID</th><th>名称</th></tr></thead>
<tbody><tr v-for="record in records" :key="record.id">
<td>{{ record.id }}</td><td>{{ record.name }}</td></tr></tbody>
</table>
</div>