Unknown action : Counter not incrementing with Vuex (VueJS)

5.7k views Asked by At

I'm using the following code to increment a counter in store.js using Vuex. Don't know why, when I click the increment button, it says:

[vuex] unknown action type: INCREMENT

store.js

import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
var store = new Vuex.Store({
  state: {
    counter: 0
  },
  mutations: {
    INCREMENT (state) {
      state.counter++;
    }
  }
})
export default store

IcrementButton.vue

<template>
  <button @click.prevent="activate">+1</button>
</template>

<script>
import store from '../store'

export default {
  methods: {
    activate () {
      store.dispatch('INCREMENT');
    }
  }
}
</script>

<style>
</style>
1

There are 1 answers

2
Saurabh On BEST ANSWER

You have to use commit in the methods as you are triggering a mutation, not an action:

export default {
  methods: {
    activate () {
      store.commit('INCREMENT');
    }
  }
}

Actions are similar to mutations, the difference being that:

  • Instead of mutating the state, actions commit mutations.
  • Actions can contain arbitrary asynchronous operations.