user3348410
user3348410

Reputation: 2833

Nuxt js how dispatch action in store and change state

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 ?

Upvotes: 1

Views: 32420

Answers (1)

Soleno
Soleno

Reputation: 1949

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.

Upvotes: 7

Related Questions