Vue项目后端返回的数组需要动态添加属性A为一个数组,当修改这个数组属性B的时候,会发现原数组的每一项的A数组的属性B也会同时修改
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <div v-for="item,index in LA" :key="index"> <div v-for="item1,index1 in item.LB" :key="index1" @click="select(index,index1)"> {{item1.key}}:{{item1.flag}} </div> </div>
data():{ return:{ LA:[{},{}] } }, created:{ let lb = [{ key: 1,flag: false }, { key: 2, flag: false }]; this.LA.forEach((item, index) => { item.LB = lb; }) }, method(){ select(index,index1){ let lb = this.LA[index].LB lb[index1].flag = true //为了视图刷新 this.LA = Object.assign({}, this.LA) //点击之后你会发现,LA的每一项的LB的index1项的flag都变成了true } }
|
解决方法一
1 2 3 4 5
| created:{ this.LA.forEach((item, index) => { item.LB = [{ key: 1,flag: false }, { key: 2, flag: false }]; }) }
|
解决方法二
1 2 3 4 5 6
| select(index, index1) { let lb = JSON.parse(JSON.stringify(this.LA[index].LB)); lb[index1].flag = true this.LA[index].LB = lb; this.LA = Object.assign({}, this.LA) },
|