vue实现列表分页
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
}
}
}
模板部分:

<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:
安装:

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;
}






