ES6 函数语法?

ES6 Functions Syntax?

我正在尝试调用我的命名空间存储:

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

导致错误:

Uncaught TypeError: Cannot read property 'toggleActive' of undefined

正在做以下工作:

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

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

您正在使用箭头函数。箭头函数 在定义它们的上下文中 关闭 this,而不是像 function 函数那样在它们被调用时设置它。例如:

// 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