鍍金池/ 問答/HTML/ vue多個組件中如何監(jiān)聽vuex中同一個action的回調(diào)

vue多個組件中如何監(jiān)聽vuex中同一個action的回調(diào)

vue單頁面應(yīng)用,在整個app入口,需要調(diào)用獲取用戶信息的接口,這個接口只調(diào)用一次,怎樣能夠在多個組件中獲取到這個接口完成的通知。

app.vue

  export default {
    mounted() {
      this.userInfo().then(res => {
        if (res.code === 200) {
            // 具體的操作
        }
      });
    },
    methods: {
      ...mapState(['userInfo'])
    }
  };

其他組件 在mounted 獲取不到userInfo

export default {
    mounted() {
        this.userInfo // 這里獲取用戶信息為空,怎樣能獲取到用戶信息呢
    },
    methods: {
      ...mapState(['userInfo'])
    }
  };

已嘗試的解決方案。
第一種通過$watch監(jiān)聽userInfo

watch: {
      userInfo(newValue){
        if(newValue.username){
          // 具體執(zhí)行函數(shù)
        }
      }
    },

第二種 在入口處用loading狀態(tài)來控制,當(dāng)在入口處action結(jié)束時,通過v-if控制渲染,
這樣存在的問題是當(dāng)這個接口掛了,整個頁面都是空白的

  <div id="app">
    <template v-if="loading">
       <router-view class="child-view"></router-view>
    </template>
  </div>   
 export default {
    data(){
      return {
        loading:false  
      }
    },
    mounted() {
      this.userInfo().then(res => {
          this.loading=true
      })
    },
    methods: {
      ...mapState(['userInfo'])
    }
  }

想問一下,有其他更好的辦法嗎?

回答
編輯回答
愚念

可以用getter,vuex的實時計算state

2017年5月6日 18:10
編輯回答
笑忘初

找到解決辦法了,創(chuàng)建一個變量保存promise,如果多個組件同時發(fā)出請求,第一個請求賦值給該變量,其他情況直接返回該變量,具體看代碼吧。

let getUserPromise = null;
let isLoading      = false;
const actions      = {
  GET_USREINFO({ commit, state }) {
    if (state.userInfo.username) {
      // 如果存在用戶信息,直接返回
      return Promise.resolve({
        code: 200,
        msg: 'ok',
        result: state.userInfo
      });
    } else {
      if (!isLoading) {
        isLoading = true;
        if (!getUserPromise) {
          getUserPromise = useSrv.getUserInfo().then((res) => {
            // 具體業(yè)務(wù)邏輯
            getUserPromise = null; // 重置,保證下次調(diào)用
            return res;
          }).finally(() => {
            isLoading = false;
          });
        }
      }
      return getUserPromise;
    }
  }
};
2017年4月21日 20:00
編輯回答
耍太極

用計算屬性就可以了,當(dāng)userinfo更新時會自動觸發(fā)組件數(shù)據(jù)更新

computed: {
    ...mapState({
        userInfo: state => state.userInfo
    }),
},
2018年4月9日 13:05
編輯回答
扯不斷
async UPDATE_USERINFO (context) {
    const userinfo = await fly.get('/my/setting/personal/loadUserInfo').catch(e => {
      console.log(e)
    })
    context.commit('SET_USERINFO', userinfo.data)
},

路由代碼
if (to.meta.requiresAuth) {
    if (token) {
      if (store.state.userInfo) {
        next()
      } else {
        store.dispatch('UPDATE_USERINFO').then(() => {
            next()
          }
        )
      }
    } else {
      title = '賬號關(guān)聯(lián)'
      next({
        path: '/login',
      })
    }
  } else {
    next()
  }

你可能 還需要一個 小工具

https://github.com/qinouz/vue... 若果又用請star

2017年11月11日 16:06