Home » vue » I am getting `unknown mutation type: mobilenav/showmobilenav` toggling a sidebar

I am getting `unknown mutation type: mobilenav/showmobilenav` toggling a sidebar

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am trying to toggle a sidebar, trying to commit a mutation when clicking a button but I keep getting [vuex] unknown mutation type: mobilenav/showmobilenav error every time.

I have tried everything I have seen online, but nothing works.

I am also trying to use the module mode instead of classic mode so, my store is structured that way below.

so below are my stores

store/index.js

export const state = () => ({
})
 
export const mutations = ({
})
 
export const actions = ({
})
 
export const getters = ({
})

store/mobilenav.js

export const state = () => ({
    mobilenav: false
})

export const mutations = () => ({
    showmobilenav(state) {
        state.mobilenav = true;
    },
    hidemobilenav(state) {
        state.mobilenav = false;
    }
})

export const getters = () => ({
    ismobilenavvisible(state) {
        return state.dropdown;
    }
})

the VUE file that calls the mutation on clicking a button

<template>
    <div class="bb" @click="showsidenav">
        <img src="~/assets/svg/burgerbar.svg" alt="" />
    </div>
</template>

<script>
export default {
    methods: {
        showsidenav() {
            this.$store.commit("mobilenav/showmobilenav");
            console.log("sidenav shown");
        },
    },
}
</script>

<style scoped>

</style>
Answers:

The problem is the exported mutations (and getters) is a function, but it needs to be an object:

store/mobilenav.js:

// export const mutations = () => ({/*...*/}) ❌
export const mutations = {/*...*/} ✅

// export const getters = () => ({/*...*/}) ❌
export const getters = {/*...*/} ✅

###

You need to do this in your store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import mobilenav from './mobilenav'

Vue.use(Vuex)

const createStore = () => new Vuex.Store({
  modules: {
    mobilenav,
  },
})

export default createStore

Then inject the store when you load your vue app:

import Vue from 'vue'
import App from '~/pages/App.vue'
import createStore from '~/store'

document.addEventListener('DOMContentLoaded', () => {
  if (document.getElementById('app-wrapper')) {
    new Vue({
      store: createStore(),
      render: h => h(App),
    }).$mount('#app-wrapper')
  }
})