Nuxt js how dispatch action in store and change state

26,464

Your mistake lies in:

this.$store.commit('openMenu')

which triggers not an action but a mutation. You don't have that mutation so therefore you get the message [vuex] unknown mutation type: openMenu.

To trigger an action you need to dispatch with dispatch:

this.$store.dispatch('openMenu')

But your action is not correct written and won't work and actions are not for mutating the state directly. They commit mutations which then mutate the state.

Solution

So in your case here it seems to be enough with a mutation so rewriting your action to a mutation should help to achieve your goal.

mutations: {
  openMenu(state) {
    state.isUserNav = true
  }
}

Have a look into mutations and actions in the vuex docs:

which describe both and their use cases quite good.

Share:
26,464
user3348410
Author by

user3348410

Updated on December 29, 2020

Comments

  • user3348410
    user3348410 over 3 years

    i have look some articles about it but i didn’t understand so much

    here is my problem :

    i have a component in nuxt

    <a @click="openMenu">Open Menu</a>
    <div v-if="isUserNav"> ...  </div>
    

    basically i want on click change to state of isUserNav to true via vuex store

    here in my component i can access to state

    import {
    mapState
    } from ‘vuex’
    
    export default {
        computed: {
            ...mapState({
                isUserNav: state => state.isUserNav
            })
        },
        methods: {
            openMenu () {
                this.$store.commit('openMenu')
            },
        }
    }
    

    here is vuex store:

    import Vuex from 'vuex'
    
    
    const createStore = () => {
        return new Vuex.Store({
            state: () => ({
                // USER NAV COMPONENT
                isUserNav: false,
                testData: "Hello"
            }),
            actions: {
                async openMenu() {
                  this.state.isUserNav = true;
                }
              }
        })
    }
    
    export default createStore
    

    there is i can’t run action exactly i can access to action but it giving

    [vuex] unknown mutation type: openMenu
    

    error in console.

    where i make mistake and what i need to do ?