在Vue.js中通过前后按钮实现数组数据分页展示(每页4条)
Vue 数组分页功能实现方案
核心实现逻辑
- 固定每页展示4条数据,用
currentPage变量记录当前页码(初始值为1) - 通过
Array.slice()方法按页码截取对应区间的数组内容:截取起始下标为(当前页码-1)*每页条数,结束下标为当前页码*每页条数 - 切换页码时增加边界判断:页码最小为1,最大为
Math.ceil(总数据长度/每页条数),避免出现空内容
修改后完整代码
<template> <v-container fluid> <v-row no-gutters> <v-col cols="12" md="12" sm="12"> <v-card> <v-row no-gutters> <v-col cols="12" md="12" sm="12" class=""> <v-row no-gutters class="d-flex"> <v-col cols="6" md="6" v-for="(item, index) in currentPageData" :key="`item-${index}`" > <v-col cols="6"> <v-card-text> <p>{{ item.id }}</p> <p>my name is : {{ item.title }}</p> </v-card-text></v-col > </v-col> </v-row> </v-col> </v-row> <v-col cols="12" md="12" sm="12" class="d-flex"> <v-col cols="6" md="6" sm="6"> <v-btn medium elevation="" color="primary" @click="backpage()" :disabled="currentPage === 1" >Back</v-btn > </v-col> <v-col cols="6" md="6" sm="6"> <v-btn medium elevation="" color="primary" @click="nextPage()" :disabled="currentPage === maxPage" >Next</v-btn > </v-col> </v-col> </v-card> </v-col> </v-row> </v-container> </template> <script> export default { data: () => ({ // 每页展示条数 pageSize: 4, // 当前页码,初始为第1页 currentPage: 1, user: [ { id: 1, title: 'Saysana', }, { id: 2, title: 'Binh', }, { id: 3, title: 'Say', }, { id: 4, title: 'Q', }, { id: 5, title: 'a', }, { id: 6, title: 'b', }, { id: 7, title: 'c', }, { id: 8, title: 'e', }, { id: 9, title: 'e', }, { id: 10, title: 'e', }, { id: 11, title: 'e', }, { id: 12, title: 'e', }, ], }), computed: { // 最大页码 maxPage() { return Math.ceil(this.user.length / this.pageSize) }, // 当前页展示的数据,自动随页码变化更新 currentPageData() { const start = (this.currentPage - 1) * this.pageSize const end = this.currentPage * this.pageSize return this.user.slice(start, end) } }, methods: { nextPage() { if (this.currentPage < this.maxPage) { this.currentPage += 1 } }, backpage() { if (this.currentPage > 1) { this.currentPage -= 1 } }, } } </script>
改动说明
- 移除了冗余的content变量和相关手动赋值逻辑,改用计算属性
currentPageData自动返回当前页对应数据,响应式更新视图 - 新增了按钮禁用状态:第一页时返回按钮不可点击,最后一页时下一页按钮不可点击,避免无效操作
- 修正了原返回页的逻辑错误,所有切片逻辑统一在计算属性中处理,维护更方便
内容的提问来源于stack exchange,提问作者Boom
相关产品推荐
相关产品推荐

