鍍金池/ 問答/HTML/ vue vuex mapState created執(zhí)行順序

vue vuex mapState created執(zhí)行順序

A組件:
  存儲:localStorage.setItem('articles', JSON.stringify(articles))
B組件:
computed: {
      ...mapState([
          "articles"
      ])
  },
  created(){
        var currentId = parseInt(this.$route.query.id);
        this.currentArticle = this.articles.filter((item)=>{
        return item.id === currentId   
        });
        this.isCollected = this.currentArticle[0].isCollected;
        this.collectNum = this.currentArticle[0].collectNum;
        console.log(this.currentArticle)
  },
vuex:
state.js:  articles:localStorage["articles"]?JSON.parse(localStorage["articles"]): []

進(jìn)入A組件后,調(diào)用接口,請求回?cái)?shù)據(jù)后,存到localStorage中,點(diǎn)擊路由跳轉(zhuǎn)到B組件,為什么在created()中 this.articles 為 [],頁面上沒有數(shù)據(jù),當(dāng)我進(jìn)入B組件后再次刷新頁面就有數(shù)據(jù)了,這里面的computed()和 created()是不是有執(zhí)行順序的問題?應(yīng)該怎么解決這個(gè)問題呢?

回答
編輯回答
骨殘心

created鉤子觸發(fā)的時(shí)候,vuex$store是已經(jīng)綁定到了vue實(shí)例上了的(準(zhǔn)確的說是在$store是在beforeCreate鉤子觸發(fā)的時(shí)候被綁定到vue實(shí)例上)。
https://github.com/vuejs/vuex...

我覺得問題的可能有兩種:

  1. 異步請求數(shù)據(jù)返回后,只存到了localStorage,并沒有存到vuex中。
    因?yàn)?code>vuex的state只會(huì)初始化一次
    僅僅articles:localStorage["articles"]?JSON.parse(localStorage["articles"]): []是不夠的,請求返回之后還應(yīng)該把state中的article重新賦值。
  2. 跳轉(zhuǎn)到B的時(shí)候 異步請求還沒有返回,vuex中的數(shù)據(jù)自然也就沒有更新了。
2018年3月21日 17:23