通过vue2来实现完整功能的自定义分页组件,请给出最简洁的详细代码,并给出每段代码的中文注释
时间: 2023-05-24 22:05:17 浏览: 81
<template>
<div class="pagination">
<button @click="prev" :disabled="currentPage <= 1">上一页</button><!--点击按钮调用prev方法,当前页码小于等于1时按钮为禁用状态-->
<button v-for="item in pages" :key="item" @click="jump(item)" :class="{ active: item === currentPage }">{{ item }}</button><!--循环页码数组,点击时调用jump方法,当前页码为active状态-->
<button @click="next" :disabled="currentPage === pageCount">下一页</button><!--点击按钮调用next方法,当前页码等于总页码时按钮为禁用状态-->
</div>
</template>
<script>
export default {
name: 'Pagination',
props: {
current: {
type: Number,
required: true
},
total: {
type: Number,
required: true
},
pageSize: {
type: Number,
default: 10
}
},
computed: {
pageCount() {
return Math.ceil(this.total / this.pageSize) /*计算总页数*/
},
currentPage: {
get() {
return this.current /*获取当前页码*/
},
set(newValue) {
this.$emit('update:current', newValue) /*向父组件发送页码更新事件*/
}
},
pages() {
const arr = [] /*定义页码数组*/
for (let i = 1; i <= this.pageCount; i++) {
arr.push(i) /*循环添加页码到数组中*/
}
return arr /*返回页码数组*/
}
},
methods: {
prev() {
this.currentPage -= 1 /*将当前页码减1*/
},
next() {
this.currentPage += 1 /*将当前页码加1*/
},
jump(page) {
this.currentPage = page /*跳转到指定页码*/
}
}
}
</script>
<style scoped>
.pagination {
display: flex;
justify-content: center;
align-items: center;
}
button {
margin: 0 10px;
outline: none;
cursor: pointer;
padding: 5px 10px;
border-radius: 2px;
border: none;
}
button[disabled] {
color: #bdd0dd;
cursor: not-allowed;
}
.active {
background-color: #409eff;
color: #fff;
}
</style>
阅读全文