Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`This` is undefined in vue.js watcher

Tags:

vue.js

vuejs2

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?

like image 726
Jackson J Avatar asked Feb 15 '17 07:02

Jackson J


People also ask

How do you watch props in Vue?

To watch for prop changes with the Vue. js Composition API, we can call the watch function. watch( () => props.

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.


1 Answers

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;         }     } } 
like image 81
Saurabh Avatar answered Sep 20 '22 06:09

Saurabh