vue3setup语法糖写一个数据分页功能
在Vue 3中,可以使用reactive函数和计算属性来实现数据分页功能。下面是一个示例代码:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="previousPage" :disabled="currentPage === 1">Previous</button>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</template>
<script>
import { reactive, computed } from 'vue';
export default {
data() {
return {
data: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
// ... more data
],
itemsPerPage: 2,
currentPage: 1
};
},
setup() {
const state = reactive({
data: this.data,
itemsPerPage: this.itemsPerPage,
currentPage: this.currentPage
});
const totalPages = computed(() => {
return Math.ceil(state.data.length / state.itemsPerPage);
});
const paginatedData = computed(() => {
const startIndex = (state.currentPage - 1) * state.itemsPerPage;
const endIndex = startIndex + state.itemsPerPage;
return state.data.slice(startIndex, endIndex);
});
function previousPage() {
if (state.currentPage > 1) {
state.currentPage--;
}
}
function nextPage() {
if (state.currentPage < totalPages.value) {
state.currentPage++;
}
}
return {
paginatedData,
currentPage: state.currentPage,
totalPages: totalPages.value,
previousPage,
nextPage
};
}
};
</script>
在这个示例中,我们使用reactive函数将data、itemsPerPage和currentPage转换为响应式数据。然后,我们使用computed函数创建totalPages和paginatedData计算属性。
totalPages计算属性根据数据总数和每页显示的项目数计算总页数。
paginatedData计算属性根据当前页码和每页显示的项目数来截取相应的数据。
previousPage和nextPage函数分别用于切换到上一页和下一页。这些函数会检查当前页码是否超出边界,并更新currentPage属性。
最后,我们在setup函数中返回需要在模板中使用的属性和方法,包括paginatedData、currentPage、totalPages、previousPage和nextPage。
在模板中,我们使用v-for指令遍历paginatedData数组,并显示每个项目的名称。我们还使用@click指令绑定previousPage和nextPage方法到上一页和下一页的按钮上,同时使用:disabled绑定属性来禁用按钮当当前页码等于第一页或最后一页时。
这样,我们就实现了一个基本的数据分页功能。你可以根据自己的需求进行调整和扩展
原文地址: https://www.cveoy.top/t/topic/ic1Q 著作权归作者所有。请勿转载和采集!