当前位置:首页 > VUE

vue.js 实现分页

2026-01-21 17:59:12VUE

Vue.js 实现分页的方法

使用计算属性分页

通过计算属性对数据进行分页处理,结合 v-for 渲染分页数据。定义一个 currentPage 变量和 itemsPerPage 变量控制当前页和每页显示数量。

data() {
  return {
    items: [], // 数据列表
    currentPage: 1,
    itemsPerPage: 10
  };
},
computed: {
  paginatedItems() {
    const start = (this.currentPage - 1) * this.itemsPerPage;
    const end = start + this.itemsPerPage;
    return this.items.slice(start, end);
  },
  totalPages() {
    return Math.ceil(this.items.length / this.itemsPerPage);
  }
}

模板中使用 paginatedItems 渲染当前页数据,并通过按钮切换页码:

<ul>
  <li v-for="item in paginatedItems" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="currentPage--" :disabled="currentPage === 1">上一页</button>
<button @click="currentPage++" :disabled="currentPage === totalPages">下一页</button>

使用第三方库

借助 vue-paginatev-pagination 等第三方库快速实现分页。以 vue-paginate 为例:

安装库:

vue.js 实现分页

npm install vue-paginate

在组件中注册并使用:

import VuePaginate from 'vue-paginate';
Vue.use(VuePaginate);

模板中直接使用组件:

vue.js 实现分页

<paginate
  :page-count="totalPages"
  :click-handler="changePage"
  :prev-text="'上一页'"
  :next-text="'下一页'"
></paginate>

后端分页结合 API

对于大数据量,建议通过后端分页。前端传递页码和每页数量参数,后端返回对应数据。

methods: {
  fetchData(page) {
    axios.get(`/api/items?page=${page}&limit=${this.itemsPerPage}`)
      .then(response => {
        this.items = response.data.items;
        this.totalPages = response.data.totalPages;
      });
  },
  changePage(page) {
    this.currentPage = page;
    this.fetchData(page);
  }
}

分页样式优化

通过 CSS 自定义分页样式,例如高亮当前页:

.pagination {
  display: flex;
  list-style: none;
}
.pagination li {
  margin: 0 5px;
  cursor: pointer;
}
.pagination li.active {
  font-weight: bold;
  color: blue;
}

在模板中绑定 active-class

<paginate
  :page-count="totalPages"
  :container-class="'pagination'"
  :page-class="'page-item'"
  :active-class="'active'"
></paginate>

以上方法可根据项目需求选择或组合使用。计算属性分页适合前端数据量较小的情况,后端分页适合大数据量场景,第三方库能快速实现标准化分页功能。

标签: 分页vue
分享给朋友:

相关文章

vue实现语音

vue实现语音

Vue 实现语音功能的方法 使用 Web Speech API Vue 可以结合 Web Speech API 实现语音识别和合成功能。Web Speech API 包含 SpeechRecognit…

vue实现公式

vue实现公式

在Vue中实现公式展示或计算可以通过多种方式实现,以下为具体方法: 使用模板插值与计算属性 若公式较简单,可直接在模板中使用插值表达式或计算属性。例如计算圆的面积: <templat…

vue实现frame

vue实现frame

Vue 中实现 iframe 的方法 在 Vue 中可以通过直接使用 <iframe> 标签或动态绑定 src 属性来实现 iframe 功能。 基本用法 <template&g…

利用vue 实现

利用vue 实现

以下是利用 Vue 实现常见功能的几种方法,分为不同场景和技术要点: 数据绑定与响应式更新 Vue 的核心特性是数据绑定,通过 v-model 实现双向绑定: <template>…

vue事件实现

vue事件实现

Vue 事件实现方法 在Vue中,事件处理是通过v-on指令或@简写来实现的。以下是几种常见的事件处理方式: 使用v-on指令绑定事件 <button v-on:click="handleC…

vue watch实现

vue watch实现

在 Vue 中实现 watch 监听数据变化 Vue 的 watch 选项用于监听数据变化并执行相应的回调函数。以下是几种常见的实现方式: 基础用法 export default { data(…