不使用后端接口前端封装分页全部代码vue
时间: 2023-12-12 15:03:06 浏览: 201
以下是一个使用Vue实现前端手动分页的示例代码,包括数据请求、分页计算、翻页逻辑和页面渲染:
```html
<template>
<div>
<ul>
<li v-for="item in pageData" :key="item.id">{{ item.name }}</li>
</ul>
<div>
<button @click="prevPage" :disabled="currentPage <= 1">上一页</button>
<span>{{ currentPage }}/{{ pageCount }}</span>
<button @click="nextPage" :disabled="currentPage >= pageCount">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
dataList: [],
pageSize: 5,
currentPage: 1
}
},
computed: {
pageData() {
var startIndex = (this.currentPage - 1) * this.pageSize;
var endIndex = startIndex + this.pageSize;
return this.dataList.slice(startIndex, endIndex);
},
pageCount() {
return Math.ceil(this.dataList.length / this.pageSize);
}
},
methods: {
fetchData() {
// 模拟数据请求
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' },
{ id: 4, name: 'Durian' },
{ id: 5, name: 'Eggplant' },
{ id: 6, name: 'Fig' },
{ id: 7, name: 'Grape' },
{ id: 8, name: 'Honeydew' },
{ id: 9, name: 'Kiwi' },
{ id: 10, name: 'Lemon' },
{ id: 11, name: 'Mango' },
{ id: 12, name: 'Nectarine' },
{ id: 13, name: 'Orange' },
{ id: 14, name: 'Pineapple' },
{ id: 15, name: 'Quince' },
{ id: 16, name: 'Raspberry' },
{ id: 17, name: 'Strawberry' },
{ id: 18, name: 'Tangerine' },
{ id: 19, name: 'Ugli fruit' },
{ id: 20, name: 'Watermelon' }
]);
}, 1000);
});
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.currentPage < this.pageCount) {
this.currentPage++;
}
},
renderPage() {
this.fetchData().then(data => {
this.dataList = data;
});
}
},
mounted() {
this.renderPage(); // 初始化页面
}
}
</script>
```
在Vue组件的mounted生命周期中调用renderPage方法,渲染数据列表和翻页按钮的UI,可以点击翻页按钮来切换当前显示的数据。需要注意的是,翻页按钮的状态(是否disabled)需要根据当前页数和总页数计算得出。
阅读全文