【问题标题】:ES6 Functions Syntax? [duplicate]ES6 函数语法? [复制]
【发布时间】:2017-07-27 08:50:39
【问题描述】:

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

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

这会导致错误:

Uncaught TypeError: Cannot read property 'toggleActive' of undefined

做以下工作:

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

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

    您正在使用箭头函数。箭头函数在定义它们的上下文中关闭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

    【讨论】:

    • 谢谢,我查看了您的链接和编辑后的答案,尽管作为箭头函数,我仍然感到困惑 - 里面的“this”应该是指 vuex 命名空间状态?
    • @panthro:他们为什么要这么做?同样,它们关闭 this,就像关闭其他变量一样。 (如果您没有看到我上面的 foo 示例,请点击刷新。)
    • 我已经检查了你的 foo 示例,所以“this”在课堂之外意味着“this”?
    • @panthro:我无法评论我看不到的代码,您没有在问题中提供太多上下文,只是对象初始化程序的部分内部。但是无论this 在该对象初始化器所在的范围内,当close 被调用时,this 将是什么。
    猜你喜欢
    • 2018-06-15
    • 2018-05-02
    • 1970-01-01
    • 2016-12-28
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    相关资源
    最近更新 更多