When doing my frontend Vue project, I have the need of executing certain steps when element(s) are pushed into the list in data
. However, when I pushed some initial values into the list in mounted()
, the console.log()
in the corresponding watch()
outputs the same value for the newVal
and oldVal
parameter values.
Javascript/Vue code:
let app = new Vue({
el: "#app",
data: {
testList: [],
},
mounted: function() {
this.testList.push('a');
this.testList.push('b');
this.testList.push('c');
},
watch: {
testList: {
handler: function(newVal, oldVal) {
console.log("new", newVal);
console.log("old", oldVal);
},
},
}
});
The console logging information:
- Why do the
newVal
andoldVal
hold the same value? - Why isn't the
watch()
function being executed three times (since I pushed three times inmounted()
)?
immediate: true
to the watch function? So it will look liketestList: { handler (...), immediate: true }
immediate: true
but nothing happened. Finally I defined the function in handler inmethods
, mapped the handler oftestList
to the function inmethods
, and exectue manually the new method I defined and it worked. But this is not elegant 😂