Reputation: 361
I'm running in a loop which should update some values inside an object on vue environment.
I tried map, foreach & for loops but the specific property (e.g Id, or show) getting always the same values.
I took the same logic to jsfiddle (i put part of the same data there for playing) and it's worked there.
Here is the code:
var data = t.data.map((item) => {
item.Status = Status.Draft;
if (item.IsSent) {
item.Status = Status.Sent;
}
return item;
});
data.forEach((item) => {
item.Buttons.forEach((b, index) => {
const id = { Id: "button_" + item.ID + "_" + index };
let show = { show: false };
switch (b.action) {
case ButtonActions.Duplicate:
case ButtonActions.Delete:
case ButtonActions.Preview: {
show = { show: true };
break;
}
case ButtonActions.Reports:
case ButtonActions.Groups: {
if (item.IsSent) {
show = { show: true };
} else {
show = { show: false };
}
break;
}
case ButtonActions.Send:
case ButtonActions.Schedule:
case ButtonActions.Edit: {
if (item.IsSent) {
show = { show: false };
} else {
show = { show: true };
}
break;
}
}
Object.assign(b, id);
Object.assign(b, show);
});
//console.log(item.Buttons);
});
button.id getting always the same id for all the buttons. button.show can be true or false but always the same at all buttons no matter what loop i'm using, the console show the expected value, then after the loop, it is strange, the property is added but with the same values all over.
It looks like I found a Vue bug! :(
Can someone help with it?
Upvotes: 0
Views: 1934
Reputation: 1432
In the vue documentation regarding Reactivity caveats for objects,
It states:
Sometimes you may want to assign a number of properties to an existing object, for example using Object.assign() or _.extend(). However, new properties added to the object will not trigger changes. In such cases, create a fresh object with properties from both the original object and the mixin object:
// instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
So, in that vein, this should help
b = Object.assign({}, b, { id, show })
Alternatively, you can use
this.$set(b, 'show', show);
this.$set(b, 'id', id);
Upvotes: 1