`this`在vue.js观察者中未定义

前端之家收集整理的这篇文章主要介绍了`this`在vue.js观察者中未定义前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有观察者的组件
props: {
    propShow: { required: true,type: Boolean }
},data() {
    return {
        show: this.propShow
    }
},watch: {
    propShow: {
        handler: (val,oldVal) => {
            this.show = val;
        }
    }
}

每当父组件更改propShow时,此组件必须更新它的show属性.这个组件也修改了show属性,这就是我需要show和propShow的原因,因为Vue.js不允许直接更改属性.

这条线

this.show = val;

导致错误

TypeError: Cannot set property 'show' of undefined

因为这个内部处理程序是未定义的.

为什么?

解决方法

您必须在此处使用函数语法,如文档 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.

所以你的代码应该是:

watch: {
    propShow: {
        handler: function(val,oldVal) {
            this.show = val;
        }
    }
}
原文链接:https://www.f2er.com/js/158884.html

猜你在找的JavaScript相关文章