【发布时间】:2018-11-29 09:40:39
【问题描述】:
我正在为大量卡片实现分页,我一次显示 10 张卡片,并希望通过单击两个按钮来显示下一个(或前 10 个)的 10 个。
我是这样做的:
export default {
...
data() {
return {
pois: [], // My list of elements
pageNumber: 0, // Current page number
};
},
props: {
size: {
type: Number,
required: false,
default: 10, // 10 cards per page
},
},
computed: {
pageCount() {
// Counts the number of pages total
const l = this.pois.length;
const s = this.size;
return Math.floor(l / s);
},
paginatedData() {
// Returns the right cards based on the current page
const start = this.pageNumber * this.size;
const end = start + this.size;
return this.pois.slice(start, end);
},
},
methods: {
nextPage() {
this.pageNumber += 1;
},
prevPage() {
this.pageNumber -= 1;
},
}
...
};
还有我的模板:
<div v-for="poi in paginatedData" :key="poi.id">
<card :poi="poi"/>
</div>
一切都应该正常工作(页面更改确实会在控制台中输出正确的卡片)但我的列表没有更新,即使每次点击都会调用计算方法。
是什么导致了这个问题?我读过它可能与缺少的 :key 值相关联,但它就在那里,并且没有直接和手动更新数组中的数据,只是被切掉了。
【问题讨论】:
-
可以
poi.id在您的数组中的每个对象上具有相同的值吗? -
在这种情况下每个 ID 都是唯一的
-
尝试使用索引键:
<div v-for="(poi, key) in paginatedData" :key="key"> -
@Christopher 您的代码有效 (proof of concept)。也许您的问题是关于如何获取数据 (pois)