vue 封装一个分页组件
时间: 2023-07-13 12:36:49 浏览: 49
好的,以下是一个简单的 Vue 分页组件的代码示例:
```html
<template>
<div>
<div v-if="totalPages > 1" class="pagination">
<a v-if="currentPage > 1" @click="goToPage(currentPage - 1)">上一页</a>
<a v-for="page in pages" :key="page"
:class="{ active: page === currentPage }"
@click="goToPage(page)">
{{ page }}
</a>
<a v-if="currentPage < totalPages" @click="goToPage(currentPage + 1)">下一页</a>
</div>
</div>
</template>
<script>
export default {
props: {
currentPage: {
type: Number,
required: true
},
totalPages: {
type: Number,
required: true
},
maxVisiblePages: {
type: Number,
default: 5
}
},
computed: {
pages() {
let startPage = Math.max(1, this.currentPage - Math.floor(this.maxVisiblePages / 2));
let endPage = Math.min(this.totalPages, startPage + this.maxVisiblePages - 1);
startPage = Math.max(1, endPage - this.maxVisiblePages + 1);
const pagesArray = [];
for (let i = startPage; i <= endPage; i++) {
pagesArray.push(i);
}
return pagesArray;
}
},
methods: {
goToPage(pageNumber) {
this.$emit('page-changed', pageNumber);
}
}
};
</script>
<style scoped>
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination a {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ccc;
border-radius: 5px;
text-decoration: none;
color: #333;
}
.pagination a.active {
background-color: #007bff;
color: #fff;
}
</style>
```
在上面的代码中,我们定义了一个分页组件,该组件接收三个 prop:
- `currentPage`:当前选中的页码。
- `totalPages`:总共的页数。
- `maxVisiblePages`:最多显示的页码数量,默认为 5。
组件内部使用了 computed 属性 `pages` 来计算需要显示的页码数组,使用了方法 `goToPage` 来触发父组件的 `page-changed` 事件,从而实现分页器的功能。
在使用该分页组件时,只需要在父组件中定义一个 `currentPage` 和 `totalPages` 的变量,然后在模板中使用 `<pagination :current-page="currentPage" :total-pages="totalPages" @page-changed="onPageChanged"></pagination>` 即可。其中,`onPageChanged` 是一个在父组件中定义的方法,用于处理页码变更事件。