Search code examples
javascriptvue.jsvuejs2vuex

Accessing Mutators in Vuex Store from Component yields Unknown Mutation Type Error


I have a number in my Vuex state. I am able to use number in my Vue component via a computed property successfully. In that Vue component, I have a method that activates a mutator in the Vuex store. This mutator then changes the value of number to a random number.

However, I am having troubles activating the mutator in the Vuex store. I receive an error when I try to activate the mutator:

[vuex] unknown mutation type: changeNumber

changeNumber is the mutator in the Vuex store that changes number to a random number.

The following is my code. I can access the store directly with this.$store.state.number from the Vue component, but cannot seem to activate the mutator changeNumber with this.$store.commit('changeNumber'). I double checked my syntax and read through multiple tutorials, and they all seemed to use this.$store.commit('mutation') successfully.

var store = new Vuex.Store({
    state: {
    number: -1
  },
  getters: {
    getNumber: function(state) {
      return state.number;
    }
  },
  mutators: {
    changeNumber: function(state) {
        state.number = Math.floor(Math.random() * 10);
    }
  }
});

var vm = new Vue({
    el: '#app',
  store: store,
  computed: {
    number: function() {
        return this.$store.getters.getNumber;
    }
  },
  methods: {
    generate: function() {
        this.$store.commit('changeNumber');
    }
  }
});

My HTML is the following:

<div v-cloak id="app">
  <button v-on:click="generate">Generate</button>
  <h3>{{ number }}</h3>
</div>

This code can be viewed in a JSFiddle here, if needed. Any help would be appreciated.


Solution

  • it should be mutations, not mutators

    var store = new Vuex.Store({
      state: {
        number: -1
      },
      getters: {
        getNumber: function(state) {
          return state.number;
        }
      },
      mutations: {
        changeNumber: function(state) {
            state.number = Math.floor(Math.random() * 10);
        }
      }
    });