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

`This` is undefined in vue.js watcher

我有 watcher 组件

props: {
    propShow: { required: true, type: Boolean }
},

data() {
    return {
        show: this.propShow
    }
},

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

每当 parent 组件更改 propShow 时,此组件必须更新它的 show 属性。 This 组件也修改 show 属性,这就是为什么我需要两者:showpropShow,因为 Vue.js 不允许直接更改属性.

这一行

this.show = val;

导致错误

TypeError: Cannot set property 'show' of undefined

因为 this 内部处理程序是 undefined.

为什么?

您必须在此处使用 function 语法,如文档 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;
        }
    }
}

"function" 不是es6代码,最好写成:

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