vue3写一个分页功能
以下是一个使用Vue 3编写的分页功能的示例:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="previousPage">上一页</button>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
import { reactive, computed } from 'vue';
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
data: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
// ... more data
],
};
},
computed: {
paginatedData() {
const startIndex = (this.currentPage - 1) * this.pageSize;
const endIndex = startIndex + this.pageSize;
return this.data.slice(startIndex, endIndex);
},
},
methods: {
previousPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
},
},
computed: {
totalPages() {
return Math.ceil(this.data.length / this.pageSize);
},
},
};
</script>
这个示例中,我们使用Vue 3的reactive函数来创建响应式的data对象,其中包含当前页码currentPage、每页显示的数据量pageSize以及整个数据集合data。我们还使用了Vue 3的computed函数来计算出当前页应该显示的数据paginatedData,以及总页数totalPages。在方法中,我们定义了previousPage和nextPage方法来切换上一页和下一页。页面中的按钮通过@click绑定到对应的方法。
在模板中,我们使用v-for指令来循环渲染每页应该显示的数据。我们使用:key来给每个列表项指定唯一的key。
这样,当用户点击上一页或下一页按钮时,会触发对应的方法进行切换,并重新计算当前页码对应的数据
原文地址: https://www.cveoy.top/t/topic/ic1G 著作权归作者所有。请勿转载和采集!