我有一個fileArray陣列來保存Vue 2 應用程式中的所有檔案物件。當我按照推薦使用更新檔案物件的屬性時,它不會重新渲染(切換“活動”類)。但是,如果陣列包含普通物件(例如但不包含檔案物件),它將起作用this.setfileArray = [{name: "John"}, {name: "Jacob"}]
代碼
<template>
<div v-for="(item, index) in fileArray">
<a-card :class="item.active ? 'active' : ''">
<img :src="item.imageUrl" @click="handleSelect(index)" />
</div>
</template>
export default {
data() {
return {
fileArray: []
}
},
methods: {
beforeUpload(file) {
// Add file object into array
this.fileArray.push(file)
return false
}
},
handleSelect(index) {
if (this.fileArray[index]) {
// Update object property inside an array with this.$set but it won't re-render
this.$set(this.fileArray[index], 'active', !this.fileArray[index].active)
}
}
}
- 下面的代碼將如何幫助重新渲染,但擴展運算子不適用于 File
beforeUpload(file) {
// Add file object into array
this.fileArray = [...this.fileArray, {...file}]
return false
}
},
- 重新分配陣列以便重新渲染的臨時解決方案
handleSelect(index) {
if (this.fileArray[index]) {
this.$set(this.fileArray[index], 'active', !this.fileArray[index].active)
this.fileArray = [...this.fileArray]
}
}
如果您遇到這種情況,請提供幫助。
uj5u.com熱心網友回復:
此代碼不起作用?:
<template>
<div v-for="item in fileArray">
<a-card :class="{ active : item.active }">
<img :src="item.imageUrl" @click="item.active = !item.active" />
</div>
</template>
uj5u.com熱心網友回復:
您:key的 v-for 元素缺少一個屬性,因此 vue 不知道應該更新哪些節點。嘗試添加哈希/唯一 id 以傳遞給鍵屬性,或使用索引作為解決方法。
<div v-for="(item, index) in fileArray" :key="item.imageUrl">
<a-card :class="item.active ? 'active' : ''">
<img :src="item.imageUrl" @click="handleSelect(index)" />
</div>
我選擇了上面的 imageUrl,因為我認為每個影像可能都是獨一無二的。如果它們沒有唯一識別符號,也可以使用“索引”。
如果這不起作用,您可以通過將密鑰系結到每次更新時替換的內容來手動強制更新,或者在最后一道防線中使用以下鏈接中的方法:
https://vuejs.org/v2/guide/components-edge-cases.html#Controlling-Updates
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414758.html
標籤:
