[Vuejs]-Define multiple variable in VUEX Mutation

0👍

Firs of all, you’re putting the plugin declaration inside of modules, and it must be outside, at the same level.

You have:

export default new Vuex.Store({ modules:{
    userStore,
    plugins: [vuexLocalStorage.plugin] },

And it should be:

export default new Vuex.Store({
modules:{
    userStore
},
  plugins: [vuexLocalStorage.plugin]
}

Second, are you specifying the store module path to persist in the vuex-persistedstate plugin?

I don’t see anywhere that declaration, and in that case, I think you should specify it as follows:

const vuexLocalStorage = new VuexPersist({ 
    paths: ['userStore'], //an array of the name of your store modules you want to persist
    key: 'vuex', 
    storage: window.localStorage 
})

And maybe would be necessary to set your module as namespaced, for example:

const namespaced = true 

const state = {
    authUser:null,
    roles:null 
} 
const mutations  = {
    SET_AUTH_USER(state,userObj){
        state.authUser = userObj
    },
    SET_USER_ROLE(state,userRole){
        state.roles = userRole      
    }
}
const actions = {
    setUserObject :({commit},userObj) => {
        commit('SET_AUTH_USER',userObj)
    },
    setUserRoles :({commit},userRole) => {
        commit('SET_USER_ROLE',userRole)
    }
}
export default {
    namespaced,
    state, 
    mutations, 
    actions
}

And also I recommend to use js-cookies instead of localStorage for security reasons, and your implementation would be as follows:

import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import userStore from '/path/to/userStore'
import * as Cookies from 'js-cookie'

export default new Vuex.Store({
    plugins: [
        createPersistedState({
            paths:['userStore'], // YOU DON'T NEED TO SPECIFY KEY NAME, AS 'vuex' IS SET BY DEFAULT
            storage: {
                getItem: key => Cookies.get(key),
                setItem: (key, value) => { 
                    Cookies.set(
                        key, 
                        value, 
                        { expires: new Date(new Date().getTime() + 20 * 60 * 1000) }) // Expiry time 60 minutes
                },
                removeItem: key => { 
                    Cookies.remove(key)
                    localStorage.removeItem('vuex')
                }
              }
            }
        )],
    modules:{
        userStore //REMEMBER TO NAMESPACE YOU MODULE!!
    }
})

And then, you could access to the persisted key from Cookies in the next way:

JSON.parse(Cookies.get("vuex")).userStore //JSON parsed to get the values

Leave a comment