vuex中获取state属性值未空是去触发action?

一般我们在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

阅读 3.2k
2 个回答

这个想法有问题

一般情况下 使用的地方指管使用
在你的项目主入口的地方加上获取用户信息的逻辑 就可以了

新手上路,请多包涵

1,可以抽出一个工具类来

function getUserInfo(store) {
  const userInfo = store.state.userInfo;
  if (!userInfo) {
    store.dispach("actUserInfo");
  }
  return userInfo;
}

computed: {
  userInfo() {
    return getUserInfo(this.$stroe);
  },
},

2,一般的业务是登录后,获取到token了就可以触发加载用户信息,可以使用vuex的watch功能

store.watch(
  (state) => {
        return state.token;
  },
  (newValue) => {
    if (newValue) {
      store.dispatch("getUserInfo");
    } else {
      store.dispatch("removeUserInfo");
    }
  }
);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题