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) roles 存储了两个变量 . 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)
我错过了什么?或者它的一个bug