`This` is undefined in vue.js watcher

I have a component with an observer

props: { propShow: { required: true, type: Boolean } }, data() { return { show: this.propShow } }, watch: { propShow: { handler: (val, oldVal) => { this.show = val; } } } 

When the parent propShow component propShow this component must update its show property. This component also modifies the show property, so I need both: show and propShow , because Vue.js does not allow you to directly change the properties.

This line

 this.show = val; 

causes an error

 TypeError: Cannot set property 'show' of undefined 

since This inside the handler is undefined .

Why?

+5
source share
1 answer

Here you will need to use the function syntax, as described in the docs here :

Note that you should not use the arrow function to define an observer (e.g. searchQuery: newValue => this.updateAutocomplete (newValue)). The reason is because the arrow functions bind the parent context, so it will not be an instance of Vue, as you expect, and this.updateAutocomplete will be undefined.

So your code should be:

 watch: { propShow: { handler: function(val, oldVal) { this.show = val; } } } 
+9
source

Source: https://habr.com/ru/post/1264226/


All Articles