【问题标题】:Define multiple variable in VUEX Mutation在 VUEX Mutation 中定义多个变量
【发布时间】:2019-04-02 10:51:02
【问题描述】:

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 存储用户令牌,roles 存储用户角色数组。当我从 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)

我错过了什么吗?或者它是一个错误

【问题讨论】:

  • 能否提供dashboard.vue的相关部分?
  • @BoussadjraBrahim 在我的问题中添加了 dashboard.vue。我只是从侧边栏调用角色并在 vuex 中调度它,然后在dashboard.vue 中调用。但它在 authUser 中给出了角色和值的 null

标签: javascript vue.js vuex


【解决方案1】:

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

你有:

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

它应该是:

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

第二,你是不是在vuex-persistedstate插件中指定要持久化的store模块路径?

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

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

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 2020-08-14
    • 2019-08-21
    • 2016-06-03
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多