鍍金池/ 問答/HTML/ 關于vue中computed和mounted的執(zhí)行問題

關于vue中computed和mounted的執(zhí)行問題

在vue組件中的computed中獲取了vuex中的屬性,然后在created生命鉤子中使用state中的屬性發(fā)送了請求發(fā)現(xiàn)mounted發(fā)送請求時參數(shù)沒有獲取到,頁面更新之后才正確:

computed: {
      ...(mapState({
        user_name: state => state.user_name,
        user_id: state => state.user_id,
        user_source: state => state.user_source,
      }))
    }
    
created() {
      request(extend(true, {}, apis.getUserConsultInfo, {
        params: {
          consult_id: this.consult_id,
          user_id: this.user_id,
          user_source: this.user_source
        }
      })).then((res) => {
        console.log(res);
      }, (errmsg) => {
        this.$message.error(errmsg);
      });
    }

這種情況怎么破?求大神解決~~

回答
編輯回答
陌璃

凡是需要處理vuex的getter中的數(shù)據(jù),均在beforeUpdate或者update階段進行。

8百年前做的一個實驗:笑納。

11個生命周期打印計算屬性值(前6個有輸出,后5個無輸出)

各生命周期打印從vuex的getter獲取到的計算屬性結(jié)果。
mounted階段的打印嘗試,其余的也類似:

    mounted(){
        console.log("mounted↓")
        console.log(this.users)
    }

從vuex getter獲取到的數(shù)據(jù):

    computed:mapGetters({
        users:'allUsers'
    }),

打印結(jié)果:
image

經(jīng)過觀察發(fā)現(xiàn),vue組件生命周期的11個階段,只有前6個階段有輸出結(jié)果。
beforeDestroy,destroyed,activated,deactivated,errorCaptured都沒有輸出結(jié)果。
在前6個階段的初始輸出結(jié)果均不是有效數(shù)據(jù),beforeCreate的undefined和其他階段的observer,均是無效數(shù)據(jù)。
直到16:28:33.740,才開始獲得有效數(shù)據(jù),且只在before和updated階段獲取到數(shù)據(jù)。

我們根據(jù)實驗結(jié)果得出一個結(jié)論:凡是需要處理vuex的getter中的數(shù)據(jù),均在beforeUpdate或者update階段進行。

2018年7月4日 13:31