Search code examples
vue.jsvuex

Vuex mapMutations isn't working as expected


I have a namespaced store (namespaced: true) and I'm trying to access it via mapMutations. When I call it via mapMutations it results in a 'not a function' error. When I call it directly via this.$store it works fine. Why does the mapMutations version not work? Pseduo-code is shown below. FWIW I'm using the latest Vue/Vuex versions.

import { mapGetters, mapMutations } from 'vuex'

computed: {
  ...mapGetters('someModule', ['foo']),
  ...mapMutations('someModule', ['bar']),
}
mounted() {
   this.$store.commit('someModule/bar'); // This works
   this.bar(); // This gives me a "this.bar() is not a function" error
   this.baz();
}
methods: {
  baz() {
   this.bar(); // This gives me a "this.bar() is not a function" error
  },
}

Solution

  • Mutation/Actions are function which stay inside methods

    ...mapMutations('someModule', ['bar']),
    

    Should be inside methods

    methods: {
      ...mapMutations('someModule', ['bar']),
      executeBar() {
         this.bar()
       }
    }
    

    For more info and comparison between methods and computed see this Method vs Computed in Vue