未更新的组件列表
List of components not updating
我有这个显示组件列表的模板:
<template>
<v-container id="container">
<RaceItem v-for="(item, index) in items" :key="item + index" />
(...)
更新数组“items”时(shift() 或 push() 新项目),显示的列表不会更新。
我确定我在 Vue 的工作原理上遗漏了一些东西......但是谁能解释一下哪里出了问题?
你能试试这样吗
将 componentKey 放在 v-container 上,并在完成推送后使用 forceRender()
key 属性需要 number | string | boolean | symbol
。推荐使用原语作为键。
最简单的用法是使用每个元素的原始唯一属性来跟踪它们:
<RaceItem v-for="item in items" :key="item.id" />
...假设您的 items
具有独特的 id
s.
如果您使用 index
作为键,每次更新数组时,您都必须将其替换为自身的更新版本(即:this.items = [...items];
- 其中 items
包含突变)。
在这种情况下,您的方法必须如下所示:
methods: {
applyChangeToItem(item, change) {
// apply change to item and return the modified item
},
updateItem(index, change) {
this.$set(
this.items,
index,
this.applyChangeToItem(this.items[index], change)
);
},
addItem(item) {
this.items = [...this.items, item];
},
removeItem(index) {
this.items = [...this.items.filter((_, i) => index !== i)];
}
}
我有这个显示组件列表的模板:
<template>
<v-container id="container">
<RaceItem v-for="(item, index) in items" :key="item + index" />
(...)
更新数组“items”时(shift() 或 push() 新项目),显示的列表不会更新。 我确定我在 Vue 的工作原理上遗漏了一些东西......但是谁能解释一下哪里出了问题?
你能试试这样吗
将 componentKey 放在 v-container 上,并在完成推送后使用 forceRender()
key 属性需要 number | string | boolean | symbol
。推荐使用原语作为键。
最简单的用法是使用每个元素的原始唯一属性来跟踪它们:
<RaceItem v-for="item in items" :key="item.id" />
...假设您的 items
具有独特的 id
s.
如果您使用 index
作为键,每次更新数组时,您都必须将其替换为自身的更新版本(即:this.items = [...items];
- 其中 items
包含突变)。
在这种情况下,您的方法必须如下所示:
methods: {
applyChangeToItem(item, change) {
// apply change to item and return the modified item
},
updateItem(index, change) {
this.$set(
this.items,
index,
this.applyChangeToItem(this.items[index], change)
);
},
addItem(item) {
this.items = [...this.items, item];
},
removeItem(index) {
this.items = [...this.items.filter((_, i) => index !== i)];
}
}