1

I'm trying to call my namespaced store:

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

Which results in the error:

Uncaught TypeError: Cannot read property 'toggleActive' of undefined

Doing the following works:

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

How can I use ES6 function syntax with vue/vuex?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

4

You're using arrow functions. Arrow functions close over the this in the context where they're defined, instead of having it set when they're called like function functions. E.g.:

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

You probably just want to use method syntax instead:

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();
    }
};

Note that this is subject to all the usual this stuff described in this question's answers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks, I've looked at your link and your edited answer, I'm still left confused though as arrow functions - with "this" inside should refer to the vuex namespaced state? – panthro Jul 27 '17 at 08:58
  • @panthro: Why would they do that? Again, they *close over* `this`, exactly like closing over other variables. (If you don't see my `foo` example above, hit refresh.) – T.J. Crowder Jul 27 '17 at 08:59
  • Ive checked your foo example, ah so "this" means "this" outside of the class? – panthro Jul 27 '17 at 09:00
  • @panthro: I can't comment on code I can't see, you haven't provided much context in the question, just the partial inside of an object initializer. But whatever `this` is in the scope where that object initializer is, is what `this` will be when `close` is called. – T.J. Crowder Jul 27 '17 at 09:04