vue中分页查询的实现

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

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

~风清扬~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值