0
我有一個數組,使用v-for
呈現爲一組Vue組件。我需要使用:key=""
否則Vue抱怨。Vue循環與索引作爲關鍵導致不可預知的行爲
我的數組有沒有唯一標識符,所以我使用索引作爲關鍵
我的循環
<card v-for="(item, index) in questions" :question="item" :key="index">{{item}}</card>
陣列具有可以具有相同的內容
[{name:"jimmy"}, {name:"billy bob"}, {name:"jimmy"}]
問題對象:只要我操作數組,結果變得非常不可預測。有時組件被正確渲染。有時在v-for
列表中間出現一個新組件,即使它被推入數組中。有時,在轉換/彈出後,所有舊組件都會保留,而新推入的組件不會出現。
代碼
if(this.questions.length > 4) this.questions.shift()
this.questions.push({name:"willy jim"})
如果我使用item.name
爲關鍵,它只要沒有重名的工作完全正常。如果我使用item.name+index
什麼太傻了,整個事情去瘋狂...
的[爲什麼不經常使用的指標作爲for循環vue.js關鍵?(可能的複製https://stackoverflow.com/questions/44531510/why-not-always-use-the-index-as-the-key-in-a-vue-js-for-loop) –