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?
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)"
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With