定义全局的简易分页组件
时间: 2023-11-06 10:04:03 浏览: 36
以下是一个简易的分页组件的实现:
```
<template>
<div class="pagination">
<span class="prev" @click="prevPage">上一页</span>
<span v-for="index in pages" :key="index"
:class="{ active: index === currentPage }"
@click="goToPage(index)">{{ index }}</span>
<span class="next" @click="nextPage">下一页</span>
</div>
</template>
<script>
export default {
name: 'Pagination',
props: {
total: {
type: Number,
required: true
},
perPage: {
type: Number,
default: 10
},
currentPage: {
type: Number,
default: 1
}
},
computed: {
pages () {
return Math.ceil(this.total / this.perPage)
}
},
methods: {
prevPage () {
if (this.currentPage > 1) {
this.$emit('page-changed', this.currentPage - 1)
}
},
nextPage () {
if (this.currentPage < this.pages) {
this.$emit('page-changed', this.currentPage + 1)
}
},
goToPage (page) {
this.$emit('page-changed', page)
}
}
}
</script>
<style scoped>
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination span {
margin: 0 10px;
cursor: pointer;
}
.pagination span.active {
font-weight: bold;
}
</style>
```
使用方法:
```
<template>
<div>
<ul>
<li v-for="item in paginatedData">{{ item }}</li>
</ul>
<pagination :total="data.length" :per-page="10" :current-page="currentPage" @page-changed="handlePageChanged" />
</div>
</template>
<script>
import Pagination from '@/components/Pagination.vue'
export default {
components: {
Pagination
},
data () {
return {
data: [/* your data */],
currentPage: 1
}
},
computed: {
paginatedData () {
const start = (this.currentPage - 1) * 10
const end = start + 10
return this.data.slice(start, end)
}
},
methods: {
handlePageChanged (page) {
this.currentPage = page
}
}
}
</script>
```
在上述代码中,我们首先定义了一个 `Pagination` 组件,并传递了三个 props:`total` 表示总数据量,`perPage` 表示每页显示的数据条数,`currentPage` 表示当前页码。然后我们使用计算属性 `pages` 计算出总页数。在模板中,我们使用 `v-for` 渲染出页码,并且在点击时触发相应的事件。最后,我们在父组件中使用 `Pagination` 组件,并监听 `page-changed` 事件,以更新当前页码。同时,使用计算属性 `paginatedData` 根据当前页码来渲染相应的数据。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)