vue项目实现分页功能
使用Element UI的分页组件
在Vue项目中,Element UI提供了现成的分页组件el-pagination,可直接集成。安装Element UI后,在组件中引入分页组件并绑定数据。
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</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>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="prevPage">上一页</button>
<span>当前页: {{ currentPage }}</span>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
dataList: [], // 原始数据
currentPage: 1,
pageSize: 5
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.dataList.slice(start, end);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
}
};
</script>
结合后端API分页
实际项目中,分页通常与后端API配合。传递页码和每页大小参数,获取分页数据。
methods: {
async fetchData() {
try {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
});
this.dataList = res.data.list;
this.total = res.data.total;
} catch (error) {
console.error(error);
}
}
}
使用Vuex管理分页状态
在大型项目中,可通过Vuex集中管理分页状态,便于多个组件共享数据。
// store.js
const store = new Vuex.Store({
state: {
currentPage: 1,
pageSize: 10,
total: 0
},
mutations: {
setPage(state, page) {
state.currentPage = page;
}
}
});
// 组件中
this.$store.commit('setPage', newPage);






