0👍
There are several weird things here.
First, you setup times
property for each day as a non-empty array – holding an empty string as a single element. But then each manageSlotTime
call either augment an existing element of that array or replace the first one with an object. That replacement seems to be the reason why you see how the first set
call kinda works. Hint: it actually doesn’t.
Second, you seem to miss the fact that this line…
var data = this.days[parentIndex].times
… doesn’t create a new array. Instead it creates another reference to the array stored in this.days[parentIndex].times
. Afterwards anything you do to data
within the loop is actually modifying the array inside your state directly. That, in turn, makes call to $set
irrelevant.
Finally, for some reasons you use for
to access a property in array by index; it’s, well, just an overcomplication. Ask yourself: if you only do some work inside that if (i === childIndex)
check, and all that work is about accessing data[i]
, why can’t you just do data[childIndex]
directly?
The bottom line – looks like your function can be rewritten like this:
manageSlotTime(event, parentIndex, childIndex) {
var timesRef = this.days[parentIndex].times;
var slot = childIndex === 0 ?
{ slot_id: '' } :
Object.assign({}, timesRef[childIndex]);
slot.time = event;
slot.slot_status = false;
this.$set(timesRef, childIndex, slot);
}
There are few questions here (what’s that special about childIndex === 0
? how slot_id
is assigned?), but this code essentially does the same as yours, but with less lines and proper $set
usage.
0👍
This most likely has to do with array Caveats. You initially assign times an array. However, vue does not detect changes to arrays.
Due to limitations in JavaScript, Vue cannot detect direct changes to an array.
If the property is an array, using the following syntax within your loop should help to overcome the problem.
this.$set(vm.items, indexOfItem, newValue)
So in your example you could use the following.
this.$set(this.days[parentIndex].times, i, dataObject);
This would look something like this.
if(childIndex == 0) {
data = {};
data.slot_id = '';
data.time = event;
data.slot_status = false;
this.$set(this.days[parentIndex].times, i, data);
}