In some situations, watch callbacks should be fired in next event loop.
<select value = '2'>
<select-item value='1'></select-item>
<select-item value='2'></select-item>
</select>
For example, when create component Select, value watcher should be triggered after select-items created.
watch : {
value: {
handler: function (val, oldVal) { /* ... */ },
nextTick: true
}
}
Since we're on API freeze and this is already feasible with pretty much the same extra code while still being an edge case, this will probably not happen.
Just move the nextTick inside of the handler or create the watcher in the mounted hook (not sure if this one is enough because I don't know the code)
@luoxlgh You can also just write your own wrapper function:
const runOnNextTick = (fn) => function handler(value, oldValue) {
this.$nextTick(() => {
fn.call(this, value, oldValue)
});
};
watch: {
// remembe not to use arrow function here, otherwise you will loose proper context
someValue: runOnNextTick(function someValueWatcher(value) {
console.log(value)
}),
}
@posva Thanks! @luoxlgh and I are in a team.
We just want call watch handler at first time. Your second advice about mounted hook helps us solve the problem. It's better than calling watch handler in nextTick each time.
Maybe we should learn more about when lifecycle hooks called.
You can just use this.$nextTick inside the handler of watch
watch: {
someData: {
handler: function(val) {
this.$nextTick(() => {
// whatever you want to do
});
},
deep: true
}
}
Most helpful comment
Since we're on API freeze and this is already feasible with pretty much the same extra code while still being an edge case, this will probably not happen.
Just move the
nextTickinside of the handler or create the watcher in themountedhook (not sure if this one is enough because I don't know the code)