vue3语法糖实现分页查询
在Vue 3中,可以使用计算属性和watch来实现分页查询的语法糖。下面是一个简单的示例:
<template>
<div>
<ul>
<li v-for="item in pagedItems" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="previousPage">Previous</button>
<button @click="nextPage">Next</button>
</div>
</template>
<script>
import { ref, computed, watch } from 'vue';
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
// ...
],
pageSize: 5,
currentPage: ref(1),
};
},
computed: {
pagedItems() {
const startIndex = (this.currentPage.value - 1) * this.pageSize;
const endIndex = startIndex + this.pageSize;
return this.items.slice(startIndex, endIndex);
},
},
methods: {
previousPage() {
if (this.currentPage.value > 1) {
this.currentPage.value--;
}
},
nextPage() {
const totalPages = Math.ceil(this.items.length / this.pageSize);
if (this.currentPage.value < totalPages) {
this.currentPage.value++;
}
},
},
watch: {
currentPage() {
// Do something when currentPage changes
this.fetchData();
},
},
mounted() {
this.fetchData();
},
methods: {
fetchData() {
// Fetch data from backend API based on currentPage and pageSize
},
},
};
</script>
在上面的示例中,我们使用了ref函数来创建一个响应式的currentPage变量。然后,我们使用计算属性pagedItems来根据当前页码和页面大小计算出要显示的数据。我们还使用了watch来监听currentPage的变化,并在变化时执行相应的操作,例如调用fetchData方法来从后端API获取数据。
在模板中,我们使用v-for指令遍历pagedItems数组,并使用key属性来保证每个项的唯一性。我们还使用了两个按钮来切换上一页和下一页,分别调用previousPage和nextPage方法来更新currentPage的值。
你可以根据自己的需求修改fetchData方法来从后端API获取数据。注意,这只是一个简单的示例,实际应用中可能需要更多的逻辑来处理分页查询
原文地址: http://www.cveoy.top/t/topic/iVd2 著作权归作者所有。请勿转载和采集!