I have component with watcher
props: { propShow: { required: true, type: Boolean } }, data() { return { show: this.propShow } }, watch: { propShow: { handler: (val, oldVal) => { this.show = val; } } } Whenever parent component changes propShow this component must update it's show property. This component also modifies show property, that's why I need both: show and propShow, because Vue.js does not allow to change properties directly.
This line
this.show = val; causes error
TypeError: Cannot set property 'show' of undefined because this inside handler is undefined.
Why?
To watch for prop changes with the Vue. js Composition API, we can call the watch function. watch( () => props.
Yes, you can setup watcher on computed property, see the fiddle.
You will have to use function syntax here, as warned in the docs here:
Note that you should not use an arrow function to define a watcher (e.g. searchQuery: newValue => this.updateAutocomplete(newValue)). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.updateAutocomplete will be undefined.
So your code should be:
watch: { propShow: { handler: function(val, oldVal) { this.show = val; } } }
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