思路
- 数据初始化:在组件的
data
中定义当前页码、每页数据量、总数据量以及数据列表。
- 获取数据:在
created
钩子函数中调用获取数据的方法,传递当前页码和每页数据量给后端 API。
- 分页逻辑:实现上一页、下一页、跳转到指定页等方法,根据当前页码和每页数据量重新请求数据。
- 展示数据:在模板中循环展示
list
中的数据,并展示分页相关的按钮和页码信息。
关键代码片段
<template>
<div>
<ul>
<li v-for="item in list" :key="item.id">{{ item.name }}</li>
</ul>
<div>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }}</span>
<button @click="nextPage" :disabled="currentPage * pageSize >= total">下一页</button>
<input type="number" v-model="targetPage" />
<button @click="goToPage">跳转</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
list: [],
targetPage: 1
};
},
created() {
this.fetchData();
},
methods: {
async fetchData() {
const response = await this.$http.get('/api/data', {
params: {
page: this.currentPage,
pageSize: this.pageSize
}
});
this.total = response.data.total;
this.list = response.data.list;
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
this.fetchData();
}
},
nextPage() {
if (this.currentPage * this.pageSize < this.total) {
this.currentPage++;
this.fetchData();
}
},
goToPage() {
const validPage = Math.max(1, Math.min(this.targetPage, Math.ceil(this.total / this.pageSize)));
if (validPage!== this.currentPage) {
this.currentPage = validPage;
this.fetchData();
}
}
}
};
</script>