vue实现翻页效果
Vue实现翻页效果的方法
使用v-for和计算属性
通过计算属性动态计算当前页显示的数据,结合v-for渲染分页内容。定义currentPage和pageSize控制分页逻辑。
<template>
<div>
<div v-for="item in paginatedData" :key="item.id">{{ item.name }}</div>
<button @click="prevPage">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
dataList: [...], // 原始数据
currentPage: 1,
pageSize: 10
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.dataList.slice(start, end);
},
totalPages() {
return Math.ceil(this.dataList.length / this.pageSize);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
}
};
</script>
使用第三方库
借助vue-paginate等专门的分页组件快速实现。安装后直接注册组件即可使用。
npm install vue-paginate
<template>
<div>
<paginate
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'<'"
:next-text="'>'"
/>
<div v-for="item in paginatedData" :key="item.id">{{ item.name }}</div>
</div>
</template>
<script>
import Paginate from 'vue-paginate';
export default {
components: { Paginate },
methods: {
changePage(pageNum) {
this.currentPage = pageNum;
}
}
// 其他逻辑与第一种方法相同
};
</script>
服务端分页
当数据量较大时,建议采用服务端分页。通过API传递页码和每页条数参数,后端返回对应数据。
methods: {
async fetchData() {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
});
this.paginatedData = res.data;
},
changePage(pageNum) {
this.currentPage = pageNum;
this.fetchData();
}
}
样式优化
为分页按钮添加CSS样式提升用户体验,例如激活状态高亮、悬停效果等。
button {
margin: 0 5px;
padding: 5px 10px;
}
button.active {
background: #42b983;
color: white;
}
button:hover:not(.active) {
background: #ddd;
}





