Search code examples
vuejs2vuexvuex-modules

Vuex state changes work in main store, but does not work in a module that is imported into the main store


First of all, good day everyone on this beautiful day. I created a simple jsfiddle that I'll use as an example to describe my problem.

https://jsfiddle.net/Mertakus/cokedgm2/13/

The problem I experience is that although this jsfiddle works to mutate the state of the message, in the Vue app im working on, I divided my store into modules, cuz my store gets bloated otherwise.

So I got a basic.js file where I'm doing the EXACT same thing as in the jsfille, and in my store.js file imported the file and registered the file. E.G:


export default {
    strict: true,

    state: {
        fields: mainFields.basic,

        message: 'Hello Vuex'
    },
    getters: {
        getBasic: state => state
    },
    mutations: {
        updateMessage (state, message) {
            state.message = message
        }
    }
}

My main store.js file:

import Vue from "vue"
import Vuex from "vuex"
import basic from "./modules/basic"

Vue.use(Vuex)

export default new Vuex.Store ({
    // strict: true, 
    modules: {
        basic
    },
    // If I uncomment this, it'll work
    // state: {
    //     message: 'Hello Vuex'
    // },
    // mutations: {
    //     updateMessage (state, message) {
    //         state.message = message
    //     }
    // }
})

For some reason, this doesn't work. With the Vue devtool I figured out that the updateMessage mutations does get fired, and the payload is updated, however it isn't displayed on the screen. When I copy -> paste the above logic in the main store.js file, it does render on the screen.


Solution

  • Since it's vuex module, you need to use this.$store.state.basic.message instead.

    const basic = {
     strict: true,
    
        state: {
    
            message: 'Hello Vuex'
        },
        getters: {
            getBasic: state => state
        },
        mutations: {
            updateMessage (state, message) {
                state.message = message
            }
        }
    }
    const store = new Vuex.Store({
         modules: {
            basic
        },
    })
    
    new Vue({ 
        store,
        el: '#app',
        computed: {
            message: {
                get () {
                   console.log(this.$store.state)
                    return this.$store.state.basic.message
                },
                set (value) {
                    this.$store.commit('updateMessage', value)
                }
            }
        },
        methods: {
            updateMessage (e) {
                this.$store.commit('updateMessage', e.target.value)
            }
        }
    })
    

    Demo here https://jsfiddle.net/ittus/0n183xty/1/