I’m trying to add/remove strings from a local data array in a method and my logic always ends up with the array always having only a single string, that being the one passed to the updateIdArr method.
Even if I remove the else
// remove portion the push never "ads" to the array. The array only ever has 1 string, the last value pushed.
What am I missing?
data() {
return {
idArr: [],
}
},
methods: {
updateIdArr(show) {
if (!this.idArr.includes(show._id)) {
// add
this.idArr.push(show._id);
} else {
// remove
this.idArr = this.idArr.filter((id) => id !== show._id);
}
console.log(this.idArr);
// always has *only* the most recent value
// e.g. ['01GDKN93GP6Q0QDBVQ3W9BDT6D', __ob__: Observer]
},
}
3
Answers
UPDATE: stupid human error
Each local data value was in a separate component. I need to emit to the parent and maintain the array there.
Your
remove
method is not doing anything as, unlikepush
,filter
does not modify the array and instead returns a new one:this.idArr = this.idArr.filter((id) => id !== show._id);
Not sure if that would break whatever this
__ob__: Observer
thing is doing though, if so you may need to filter it in-place using a for loop or something.can you try this?