当前位置:首页 > VUE

vue实现列表分页

2026-02-17 01:46:37VUE

Vue 实现列表分页的方法

使用计算属性实现分页数据

通过计算属性对原始数据进行分页处理,结合 v-for 渲染分页后的数据片段。

data() {
  return {
    items: [],       // 原始数据
    currentPage: 1,  // 当前页码
    perPage: 10      // 每页条数
  }
},
computed: {
  paginatedItems() {
    const start = (this.currentPage - 1) * this.perPage
    const end = start + this.perPage
    return this.items.slice(start, end)
  },
  totalPages() {
    return Math.ceil(this.items.length / this.perPage)
  }
}

模板部分示例:

<ul>
  <li v-for="item in paginatedItems" :key="item.id">{{ item.name }}</li>
</ul>

添加分页导航控件

创建分页按钮组件,允许用户切换不同页码。

methods: {
  goToPage(page) {
    if (page >= 1 && page <= this.totalPages) {
      this.currentPage = page
    }
  }
}

模板部分:

vue实现列表分页

<div class="pagination">
  <button @click="goToPage(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
  <span v-for="page in totalPages" :key="page">
    <button @click="goToPage(page)" :class="{ active: page === currentPage }">{{ page }}</button>
  </span>
  <button @click="goToPage(currentPage + 1)" :disabled="currentPage === totalPages">下一页</button>
</div>

结合后端API的分页实现

当数据量较大时,建议采用后端分页,通过API参数控制分页。

methods: {
  async fetchData(page = 1) {
    const response = await axios.get('/api/items', {
      params: {
        page,
        per_page: this.perPage
      }
    })
    this.items = response.data.items
    this.totalPages = response.data.total_pages
    this.currentPage = page
  }
},
created() {
  this.fetchData()
}

使用第三方分页组件

可以集成现成的分页组件如 vue-paginate

安装:

vue实现列表分页

npm install vue-paginate

使用示例:

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

模板:

<paginate
  :page-count="totalPages"
  :click-handler="goToPage"
  :prev-text="'<'"
  :next-text="'>'"
  :container-class="'pagination'"
  :page-class="'page-item'">
</paginate>

样式优化建议

为分页组件添加基础CSS样式:

.pagination {
  display: flex;
  list-style: none;
  padding: 0;
}

.pagination button {
  margin: 0 5px;
  padding: 5px 10px;
  border: 1px solid #ddd;
  background: #fff;
  cursor: pointer;
}

.pagination button.active {
  background: #42b983;
  color: white;
  border-color: #42b983;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

标签: 分页列表
分享给朋友:

相关文章

vue组件传值实现分页

vue组件传值实现分页

Vue组件传值实现分页的方法 在Vue中实现分页功能,通常需要父子组件之间的数据传递。以下是几种常见的传值方式: 使用props传递数据 父组件通过props向子组件传递当前页码和总页数等分页信息…

vue实现下拉分页思想

vue实现下拉分页思想

实现下拉分页的基本思想 下拉分页(Infinite Scroll)是一种常见的分页加载方式,当用户滚动到页面底部时自动加载下一页数据。Vue 中可以通过监听滚动事件或使用第三方库实现。 监听滚动事件…

react 如何分页

react 如何分页

分页实现方法 在React中实现分页功能可以通过多种方式完成,具体取决于数据来源(如API或本地数据)和UI库的选择。以下是常见的实现方法: 使用本地数据分页 对于存储在组件状态或Contex…

h5实现左右分页

h5实现左右分页

实现左右分页的HTML5方法 在HTML5中实现左右分页效果可以通过多种方式完成,以下是几种常见的方法: 使用CSS Flexbox布局 Flexbox是一种现代的布局方式,可以轻松实现左右分页效…

vue实现前端分页

vue实现前端分页

实现前端分页的方法 在Vue中实现前端分页通常需要结合数据截取和分页组件。以下是常见的实现方式: 基础实现方案 数据准备 定义总数据数组和分页相关变量: data() { return {…

vue实现筛选列表

vue实现筛选列表

Vue 实现筛选列表的方法 数据绑定与列表渲染 使用 v-for 指令渲染原始列表,绑定到 data 中的数组。例如: data() { return { items: […