Vue: Add nextTick option to $watch api

Created on 16 Apr 2018  Â·  4Comments  Â·  Source: vuejs/vue

What problem does this feature solve?

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.

What does the proposed API look like?

watch : {
    value: {
        handler: function (val, oldVal) { /* ... */ },
        nextTick: 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 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)

All 4 comments

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
       }
 }

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fergaldoyle picture fergaldoyle  Â·  3Comments

robertleeplummerjr picture robertleeplummerjr  Â·  3Comments

lmnsg picture lmnsg  Â·  3Comments

gkiely picture gkiely  Â·  3Comments

franciscolourenco picture franciscolourenco  Â·  3Comments