Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing watcher value in watcher

Tags:

vue.js

vuejs2

I have some code similar to below:

<some_component v-model="some_value" />
{{ some_value }}

In my script code I have the following:

 ...
 data() {
     return {
         some_value: 'initial'
     };
 },
 ...
 watch: {
     some_value(new_value, old_value) {
         // Small subset of code, actual code does much more than this
         if (new_value === 'some_new_value') {
              this.some_value = 'can not use that value';
         }
     }
 },
 ...

So everything seems be functioning fine, until I try to change the value I'm watching from within the watcher itself. I would expect the watcher to fire again, but it doesn't and although value of the v-model changes, it does't change in the UI.

I tried using this.$forceUpdate() before and after change but it didn't seem to work.

Can anyone tell me what I'm doing wrong here?

like image 424
Sean Avatar asked Oct 19 '17 21:10

Sean


1 Answers

You shouldn't update the value you're watching in its watcher, but if you have no other choice you can use $nextTick

some_value(new_value, old_value) {
  // Small subset of code, actual code does much more than this
  if (new_value === 'some_new_value') {
    this.$nextTick(() => {
      this.some_value = 'can not use that value';
    })
  }
}

another way to do it (and the best in my opinion) is directly overriding v-model. as you may know, v-model="some_value" is shorthand for :value="some_value" and @input="some_value=$event". so you can do what you're trying to like this:

<some-component
  :value="some_value" 
  @input="some_value=some_method($event)"
/>
like image 152
user14728407 Avatar answered Oct 23 '22 05:10

user14728407