每当我使用axios响应将数据发送到vuex存储时,例如 .
** Sidebar.vue **
created(){
this.getRoles();
},
methods: {
getRoles(){
var _this = this
var roles = null
this.$http.get('/api/userroles/userroles').then(function(response){
// Passing data to vuex within response
_this.$store.dispatch('setUserRoles', response.data.data)
}
}
check_role(){
}
}
当我在侧栏中像 console.log(this.$store.state.userStore.roles) 一样控制台它有 Value ,但是当我在仪表板中控制它时它返回null并且当我看到vuex chrome扩展它包含值(在下面提供的图像)时,但在仪表板中它返回null
eg in dashboard
** dashboard.vue **
created(){
console.log(this.$store.state.userStore.roles)
// null
},
现在,当我在axios响应之外调度到vuex时,它完美地运行并在仪表板中给出值,但是它的抛出错误如错误:[vuex]不要在变异处理程序之外改变vuex存储状态 . 例如 .
created(){
this.getRoles();
},
methods: {
getRoles(){
var _this = this
var roles = null
this.$http.get('/api/userroles/userroles').then(function(response){
_this.roles_data = response.data.data
}
_this.$store.dispatch('setUserRoles', _this.roles_data)
}
}
例如,如果我在axios外部使用派遣,它会在仪表板中给出 Value
** dashboard.vue **
created(){
console.log(this.$store.state.userStore.roles)
// (25) [{…}, {…}, {…}, __ob__: Observer]
},
我错过了什么?
2 回答
您正在尝试在进行api调用之前控制store.state.userStore.roles . 避免在created()中访问商店值
试试这个:
并且不要尝试在创建的方法中控制角色 . 因为它无法工作,axios是异步的,你将在数据到达之前控制状态 . 如果,也在axios回调中控制它: