You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Bootstrap分页表格如何获取当前页面显示的行数?

Vue Bootstrap 表格获取当前页显示行数实现方案

在Vue Bootstrap的b-table组件中,要实现“显示n条数据,共24条”的效果,核心是拿到当前页实际渲染的数据条数(最后一页可能不满设定的每页行数),下面是两种靠谱的实现方式:


方式1:利用表格实例的内置方法(推荐)

b-table提供了getCurrentPageItems()方法,可以直接获取当前页的所有数据,取其长度就是当前页显示的行数,这种方法自动适配分页、筛选等场景,无需手动计算。

代码示例

<template>
  <div>
    <!-- 表格组件,绑定分页属性并添加ref -->
    <b-table
      :items="allItems"
      :per-page.sync="pageSize"
      :current-page.sync="currentPage"
      ref="dataTable"
    >
      <!-- 自定义表格列 -->
      <template #cell(name)="{ item }">
        {{ item.name }}
      </template>
    </b-table>

    <!-- 显示统计文本 -->
    <p class="mt-3">显示 {{ currentPageCount }} 条数据,共 {{ totalCount }} 条</p>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

// 模拟总数据(24条)
const allItems = ref(Array.from({ length: 24 }, (_, idx) => ({
  id: idx + 1,
  name: `数据项 ${idx + 1}`
})));

// 分页相关变量
const pageSize = ref(10); // 动态变化的每页行数
const currentPage = ref(1);
const dataTable = ref(null); // 表格实例引用

// 计算总条数
const totalCount = computed(() => allItems.value.length);

// 计算当前页显示条数
const currentPageCount = computed(() => {
  if (!dataTable.value) return 0;
  // 调用表格内置方法获取当前页数据,取长度
  return dataTable.value.getCurrentPageItems().length;
});
</script>

方式2:手动计算当前页数据条数

如果不想依赖表格实例,也可以通过当前页码和每页行数手动计算,逻辑是:

  1. 计算当前页的起始索引:(currentPage - 1) * pageSize
  2. 计算当前页的结束索引:起始索引 + pageSize
  3. 当前页条数 = 结束索引和总条数的较小值 - 起始索引

代码示例

<template>
  <div>
    <b-table
      :items="allItems"
      :per-page.sync="pageSize"
      :current-page.sync="currentPage"
    >
      <!-- 表格列定义 -->
    </b-table>
    <p>显示 {{ currentPageCount }} 条数据,共 {{ totalCount }} 条</p>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

const allItems = ref(Array.from({ length: 24 }, (_, idx) => ({ id: idx + 1, name: `数据项 ${idx + 1}` })));
const pageSize = ref(10);
const currentPage = ref(1);

const totalCount = computed(() => allItems.value.length);

// 手动计算当前页条数
const currentPageCount = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return Math.min(end, totalCount.value) - start;
});
</script>

注意事项

  • 如果表格开启了筛选/搜索功能,总条数要改用表格的filteredItems长度,这时候方式1的内置方法会自动处理筛选后的数据,比手动计算更省心。
  • per-page.sync和current-page.sync是双向绑定,能实时响应分页控件的变化(比如用户切换每页行数或页码)。

内容的提问来源于stack exchange,提问作者Shannia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:45:40