ES6函数语法?

时间:2017-07-27 08:50:39

标签: javascript vue.js vuejs2 vuex

我正在尝试调用我的命名空间商店:

methods: {
    ...mapActions('Modal', [
        'toggleActive',
    ]),
    close: () => {
        this.toggleActive();
    }

导致错误:

Uncaught TypeError: Cannot read property 'toggleActive' of undefined

执行以下工作:

close: function() {
    this.toggleActive();
}

如何在vue / vuex中使用ES6函数语法?

1 个答案:

答案 0 :(得分:4)

您正在使用箭头功能。箭头函数在定义它们的上下文中关闭 this,而不是在它们像function函数一样被调用时设置它。 E.g:

// Whatever `this` means here
var o = {
    foo: () => {
        // ...is what `this` means here when `foo` is called
    }
};

您可能只想使用方法语法:

methods: {
    // (I'm using a simple method for toggleActive just for clarity; if you're
    // transpiling with something that understands rest notation for
    // objects, your `mapActions` thing is probably fine *provided* that
    // the functions it creates aren't also arrow functions
    toggleActive() {
        // ...
    },
    close() {
        ths.toggleActive();
    }
};

请注意,这取决于所有常见的this内容described in this question's answers