分页实现vue
分页实现方法(Vue)
使用Element UI分页组件
安装Element UI库后,可以直接使用其分页组件。在模板中添加el-pagination,通过v-model绑定当前页码,设置page-size和total属性。
<template>
<el-pagination
v-model:current-page="currentPage"
:page-size="pageSize"
:total="total"
@current-change="handleCurrentChange"
/>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 根据currentPage和pageSize获取数据
}
}
}
</script>
自定义分页逻辑
如果不使用UI库,可以手动实现分页逻辑。计算总页数并渲染页码按钮,通过点击事件切换当前页。
<template>
<div>
<button
v-for="page in totalPages"
:key="page"
@click="currentPage = page"
>
{{ page }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
totalItems: 100
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.pageSize)
}
},
watch: {
currentPage() {
this.fetchData()
}
},
methods: {
fetchData() {
// 获取数据逻辑
}
}
}
</script>
后端API分页
通常分页需要后端配合,传递page和pageSize参数。使用axios发送请求时,将这些参数添加到查询字符串中。
methods: {
fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
pageSize: this.pageSize
}
}).then(response => {
this.data = response.data.items
this.total = response.data.total
})
}
}
分页数据过滤
在前端处理分页数据时,可以使用数组的slice方法对数据进行分页。适用于数据量较小且不需要后端分页的情况。
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
}
}
分页样式优化
为当前页码添加高亮样式,提升用户体验。通过动态class绑定实现选中状态。
<template>
<button
v-for="page in totalPages"
:key="page"
@click="currentPage = page"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</template>
<style>
.active {
background-color: #409eff;
color: white;
}
</style>






