vu e封装分页组件
时间: 2024-10-10 12:15:56 浏览: 71
Vue.js中封装分页组件通常是为了提高代码复用性和模块化,使得在多个地方都能轻松地显示数据列表,并处理分页逻辑。以下是一个简单的步骤来创建这样一个分页组件:
1. **创建组件**:首先,创建一个新的Vue组件,例如`Pagination.vue`,并设置它接受必要的属性,如当前页、每页显示的条数、总记录数等。
```html
<template>
<div class="pagination">
<button v-if="prevPage" @click="prevPage()">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button v-if="nextPage" @click="nextPage()">下一页</button>
</div>
</template>
<script>
export default {
props: {
currentPage: {
type: Number,
required: true,
},
pageSize: {
type: Number,
required: true,
},
totalCount: {
type: Number,
required: true,
},
},
computed: {
totalPages() {
return Math.ceil(this.totalCount / this.pageSize);
},
prevPage() {
return this.currentPage > 1;
},
nextPage() {
return this.currentPage < this.totalPages;
}
},
methods: {
prevPage(),
nextPage(),
}
}
</script>
```
2. **使用组件**:在需要分页的地方,只需要导入并传入对应的数据即可。
```html
<template>
<div>
<ul>
<!-- 你的数据列表 -->
<li v-for="(item, index) in paginatedData" :key="index">{{ item }}</li>
</ul>
<pagination :currentPage="currentPage" :pageSize="pageSize" :totalCount="totalCount"/>
</div>
</template>
<script>
import Pagination from '@/components/Pagination.vue';
export default {
components: {
Pagination,
},
data() {
return {
currentPage: 1,
pageSize: 10,
totalCount: yourTotalItemCount,
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.data.slice(start, end);
},
}
};
</script>
```
阅读全文