【发布时间】:2022-01-12 05:38:50
【问题描述】:
我有一个 fileArray 数组来保存 Vue 2 应用程序中的所有 文件对象。当我按照建议使用this.set 更新文件对象 的属性时,它不会重新渲染(切换“活动”类)。但是,如果数组包含正常的 Object,例如 fileArray = [{name: "John"}, {name: "Jacob"}],但不包含 File Object
代码
<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]
}
}
如果您遇到这种情况,请提供帮助。
【问题讨论】:
标签: javascript arrays vue.js object reactive