57

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?

2 Answers 2

110

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Any idea how to write a setter for a singular, as in not derived out of other properties, computed property?
object's handler keyword can be dropped.
1

"function" is not es6 code, you should better write:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.