Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use "this" in mapMutations spread inside Vue instance methods?

I want to set Vuex mutations as follows:

export default {
    props: {
        store: String
    },
    methods: {
        ...mapMutations({
            changeModel: `${this.store}/changeModel`
        })
    }
}

But I catch the error:

Uncaught TypeError: Cannot read property 'store' of undefined

How do I correctly use props inside the module mutation name?

I want to map this.$store.commit('form1/changeModel'), where form1 is set from props.

like image 298
mcmimik Avatar asked Aug 29 '18 19:08

mcmimik


2 Answers

Vuex helper mapMutations can be used with a function which works with this.

There does not seem to be a doc for this, but the Vuex unit test helpers.spec.js illustrates the pattern.

const vm = new Vue({
  store,
  methods: mapMutations({
    plus (commit, amount) {
      commit('inc', amount + 1)
    }
  })
})

As a bonus, the function allows passing a parameter to the mutation, which is a common requirement.

Your code changes would be:

export default {
  props: {
    store: String
  },
  methods: {
    ...mapMutations({
      changeModel(commit) { commit(`${this.store}/changeModel`) }
    })
  }
}

The call within your component is just changeModel() - mapMutations is taking care of injecting the commit parameter.

Note, I am not sure this is adding much except some extra noise (compared to a simple this.$store.commit()), but perhaps your requirement is more complicated than the example code.

like image 73
Richard Matsen Avatar answered Nov 04 '22 00:11

Richard Matsen


I think there is no way to bind this on mapActions. But you can call it with $store.dispatch

methods: {
  changeModel() {
    this.$store.dispatch(`${this.store}/changeModel`);
  }
}
like image 3
Jae Woo Woo Avatar answered Nov 03 '22 23:11

Jae Woo Woo