我有一个包含37个项目的列表,我想在表格中的四个不同页面中显示这些项目。
如何使用javascript
或vue.js
拆分这些项目并在4个不同的页面中显示?
如果您想要自己的实现,可以过滤项目列表,并根据您在一个页面中需要的项目将其拆分为子数组。下面是一个如何实现这一目标的示例代码。
示例组件的内容:
data() {
return {
currentPage: 1,
itemsPerPage: 3,
items: [{id: 1, title: 'test1'},{id: 2, title: 'test2'},{id: 3, title: 'test3'},{id: 4, title: 'test4'},{id: 5, title: 'test5'},{id: 6, title: 'test6'},{id: 7, title: 'test7'},{id: 8, title: 'test8'}]
}
},
computed: {
paginatedItems() {
let page = 1;
return [].concat.apply(
[],
this.items.map( (item, index) =>
index % this.itemsPerPage ?
[] :
{ page: page++, items: this.items.slice(index, index + this.itemsPerPage)}
)
);
},
currentPageItems() {
let currentPageItems = this.paginatedItems.find(pages => pages.page == this.currentPage);
return currentPageItems ? currentPageItems.items : [];
}
},
methods {
changePage(pageNumber) {
if(pageNumber !== this.currentPage)
this.currentPage = pageNumber;
}
}
示例模板:
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr v-for="item in currentPageItems" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.title}}</td>
</tr>
</tbody>
</table>
<div>
<span>Page:</span>
<button v-for="i in paginatedItems.length" class="btn btn-secondary mr-1" :class="{'btn-success' : currentPage === i }" @click="changePage(i)">
{{i}}
</button>
</div>