I have an fileArray array to hold all the File Object in a Vue 2 app. When I update a property of an File Object using this.set as recommended, it will not re-render (to toggle "active" class). However, it would work if the array holds normal Object such as fileArray = [{name: "John"}, {name: "Jacob"}] but not the File Object
Code
<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)
}
}
}
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]
}
}
Please help if you experienced this.
This code don't work ?:
<template>
<div v-for="item in fileArray">
<a-card :class="{ active : item.active }">
<img :src="item.imageUrl" @click="item.active = !item.active" />
</div>
</template>
You're missing a :key attribute on your v-for element, so vue doesn't know which of the nodes should be updated. Try adding a hash/unique id to pass to the key attribute, or use index as a workaround.
<div v-for="(item, index) in fileArray" :key="item.imageUrl">
<a-card :class="item.active ? 'active' : ''">
<img :src="item.imageUrl" @click="handleSelect(index)" />
</div>
I chose imageUrl above as I figured it might be unique for each image. If they have no unique identifiers, 'index' could be used as well.
If that doesn't work, you can manually force an update by binding the key to something you replace on each update, or in the final line of defense use the method in this link below:
https://vuejs.org/v2/guide/components-edge-cases.html#Controlling-Updates