VueJS:无法从观察程序内部更新组件属性

Nag*_*Nag 2 javascript vue.js vuejs2

我正在构建一个使用Vuex的Vue 2 Webpack应用程序。我正在尝试通过观察从Vuex存储获取数据的计算属性来更新组件的本地状态。这是<script></script>我的组件部分内部的样子:

export default {
    name: 'MyComponent',

    data() {
        return {
            // UI
            modal: {
            classes: {
                'modal__show-modal': false,
            },
            tags: [],
            },
        };
    },

    computed: {
        tagList() {
            return this.$store.getters.tagList;
        },
    },

    watch: {
        tagList: (updatedList) => {
            this.modal.tags = updatedList;
        },
    },
};
Run Code Online (Sandbox Code Playgroud)

如您所见,我有一个名为tagList的计算属性,该属性从商店中获取数据。我有一个监视tagList的观察器,以便每当商店的数据更改时,我都可以更新modal.tags到新值。

根据Vue文档,我可以调用this.propertyName和更新本地组件状态,但是当我调用时this.modal.tags = updatedList;,出现以下错误:

[Vue warn]: Error in callback for watcher "tagList": "TypeError: Cannot set property 'tags' of undefined"

即使看起来与Vue.js文档中的内容没有什么不同,为什么也会发生此错误?

acd*_*ior 7

不要使用箭头功能。

更改自:

watch: {
    tagList: (updatedList) => {
        this.modal.tags = updatedList;
    },
},
Run Code Online (Sandbox Code Playgroud)

至:

watch: {
    tagList(updatedList) {              // changed this line
        this.modal.tags = updatedList;
    },
},
Run Code Online (Sandbox Code Playgroud)

Vue文档几次提到了这一点:

不要 在options属性或回调函数上使用箭头功能,例如created: () => console.log(this.a)vm.$watch('a', newValue => this.myMethod())。由于箭头函数绑定到父上下文,this因此不会像您期望的那样成为Vue实例,通常会导致诸如

Uncaught TypeError: Cannot read property of undefined
Run Code Online (Sandbox Code Playgroud)

要么

Uncaught TypeError: this.myMethod is not a function
Run Code Online (Sandbox Code Playgroud)

基本上,这是一个上下文/范围的问题。使用箭头函数时,this不会引用Vue实例,而是引用组件声明所在的封闭上下文(可能是window)。