用vue3写分页
以下是一个简单的分页组件示例,使用Vue3编写:
<template>
<div>
<div v-if="totalPages > 1">
<button :disabled="currentPage === 1" @click="currentPage--">上一页</button>
<button v-for="page in pages" :key="page" :class="{ active: page === currentPage }" @click="currentPage = page">{{ page }}</button>
<button :disabled="currentPage === totalPages" @click="currentPage++">下一页</button>
</div>
</div>
</template>
<script>
import { computed, reactive } from 'vue';
export default {
props: {
totalItems: {
type: Number,
required: true
},
itemsPerPage: {
type: Number,
default: 10
}
},
setup(props) {
const state = reactive({
currentPage: 1
});
const totalPages = computed(() => {
return Math.ceil(props.totalItems / props.itemsPerPage);
});
const pages = computed(() => {
const pageArray = [];
for (let i = 1; i <= totalPages.value; i++) {
pageArray.push(i);
}
return pageArray;
});
return {
state,
totalPages,
pages
};
}
};
</script>
<style>
button {
margin-right: 5px;
}
button.active {
background-color: #007bff;
color: #fff;
}
</style>
使用方法:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item">{{ item }}</li>
</ul>
<pagination :total-items="data.length" :items-per-page="10" />
</div>
</template>
<script>
import Pagination from './Pagination.vue';
export default {
components: {
Pagination
},
data() {
return {
data: Array.from({ length: 100 }, (_, i) => i + 1)
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.data.slice(start, end);
}
},
setup() {
const currentPage = ref(1);
const itemsPerPage = ref(10);
return {
currentPage,
itemsPerPage
};
}
};
</script>
在这个示例中,我们使用了Vue3的新特性setup(),引入了reactive和computed函数。使用reactive创建响应式对象来存储当前页数,使用computed计算总页数和页码数组。在模板中,使用v-for循环渲染页码按钮,并根据当前页数添加“active”类。按钮的点击事件会更新当前页数。disabled属性用于禁用上一页和下一页按钮。
在父组件中,使用computed计算分页后的数据数组。setup()函数返回当前页数和每页显示的项目数,这些值可以在模板中使用。
原文地址: https://www.cveoy.top/t/topic/06S 著作权归作者所有。请勿转载和采集!