在VUEX突变中定义多个变量

时间:2018-10-29 13:34:39

标签: javascript vue.js vuex

store.js

import Vue from 'vue';
import Vuex from 'vuex';
import userStore from './user/userStore.js';
import VuexPersist  from "vuex-persistedstate";
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'


const vuexLocalStorage = new VuexPersist({
  key: 'vuex', // The key to store the state on in the storage provider.
  storage: window.localStorage, // or window.sessionStorage or localForage
})

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

strict:debug
})

userStore.js

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 {
    state, mutations, actions
}

Sidebar.vue

created(){
    this.getRoles();
},
methods: {
    getRoles(){
        var _this = this
        _this.roles_data = response.data
        _this.$store.dispatch('setUserRoles',_this.roles_data)
        _this.fetch_roles()
    }
    fetch_roles(){
        console.log(this.$store.state.userStore.roles)
        // OUTPUT
        // (3) [{…}, {…}, {…}, __ob__: Observer]

        console.log(this.$store.state.userStore)
        // OUTPUT
        // {__ob__: Observer}
        // authUser: "NqStDm8ol3QGtoh0hzL7yhC3NP3HV0ktYKmYHI8TNiCjG4T4tLlv3pOEWFdA5CEh"
        // roles: Array(3)      
    }
}

Dashboard.vue

created(){
    console.log(this.$store.state.userStore.roles)
    // OUTPUT
    // null

    console.log(this.$store.state.userStore)
    // OUTPUT
    // {__ob__: Observer}
    // authUser: "NqStDm8ol3QGtoh0hzL7yhC3NP3HV0ktYKmYHI8TNiCjG4T4tLlv3pOEWFdA5CEh"
    // roles: Array(3)
}
嗨     我正在使用vuex来存储用户角色访问权限。我在商店 1)authUser 2)角色中存储了两个变量。 authUser 存储用户令牌,角色存储用户角色数组。当我从api获取角色时,我将角色分派到 _this。$ store.dispatch('setUserRoles',_ this.roles_data)。当我在侧边栏中进行控制台操作时,会得到这样的输出

console.log(this.$store.state.userStore.roles)
(3) [{…}, {…}, {…}, __ob__: Observer]

console.log(this.$store.state.userStore)
{__ob__: Observer}
authUser: "NqStDm8ol3QGtoh0hzL7yhC3NP3HV0ktYKmYHI8TNiCjG4T4tLlv3pOEWFdA5CEh"
roles: Array(3)

但是当我在创建的功能中的仪表板中进行控制台操作时,它会返回 roles null

console.log(this.$store.state.userStore.roles)
null

console.log(this.$store.state.userStore)
{__ob__: Observer}
authUser: "NqStDm8ol3QGtoh0hzL7yhC3NP3HV0ktYKmYHI8TNiCjG4T4tLlv3pOEWFdA5CEh"
roles: Array(3)

我错过了什么吗?或其错误

1 个答案:

答案 0 :(得分:0)

首先,您将plugin声明放在modules的内部,并且它必须在同一级别的外部。

您有:

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

应该是:

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

第二,您是否要指定存储模块路径以保留在vuex-persistedstate插件中?

我看不到该声明的任何地方,在这种情况下,我认为您应该按以下方式指定它:

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

也许可能需要将模块设置为命名空间,例如:

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
}

出于安全原因,我还建议使用js-cookies代替localStorage,您的实现如下:

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!!
    }
})

然后,您可以通过以下方式从Cookies中访问持久密钥:

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