首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ES6函数语法?

ES6函数语法?
EN

Stack Overflow用户
提问于 2017-07-27 08:50:39
回答 1查看 96关注 0票数 1

我想给我的同名店打电话:

代码语言:javascript
复制
methods: {
    ...mapActions('Modal', [
        'toggleActive',
    ]),
    close: () => {
        this.toggleActive();
    }

这将导致错误:

代码语言:javascript
复制
Uncaught TypeError: Cannot read property 'toggleActive' of undefined

从事以下工作:

代码语言:javascript
复制
close: function() {
    this.toggleActive();
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-27 08:54:20

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

代码语言:javascript
复制
// Whatever `this` means here
var o = {
    foo: () => {
        // ...is what `this` means here when `foo` is called
    }
};

您可能只想使用方法语法来代替:

代码语言:javascript
复制
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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45345784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档