一般我们在vuex中会定义state, action, mutation;如下:
state: {
userInfo: null
}
actions: {
actUserInfo({commit}){
const userInfo = // 接口获取
commit('commitUserInfo', userInfo)
}
}
mutations: {
userInfo(state, data){
state.userInfo = data;
}
}
当我们在页面获取时 使用 computed:
computed: {
userInfo(){
return this.$store.state.userInfo;
}
}
但是我们在获取userInfo的时候可以此时还没有userInfo的数据,所以我们会进行判断,没有数据就通过action中的 actUserInfo 获取
computed: {
userInfo(){
const userInfo = this.$store.state.userInfo;
if (!userInfo){
this.$store.dispach('actUserInfo')
}
return userInfo;
}
}
这样在多出需要使用到userInfo信息时很不方便,能否有好的办法,在页面获取时依旧只用return this.$store.state.userInfo;
;但是在state获取时判断,数据为空就主动触发actUserInfo
这个想法有问题
一般情况下 使用的地方指管使用
在你的项目主入口的地方加上获取用户信息的逻辑 就可以了