天天看點

[Vue]“TypeError: Cannot read property ‘id‘ of undefined“的解決方法

原因一:異步請求資料還沒到,vue在拿到資料之前就已經渲染完了頁面

解決方案

資料為數組:
hotspotList[i]&&hotspotList[i].itemid

例如
 		<div style="display: flex;justify-content: space-between">
            <p class="item-title">{{hotspotList[i]&&hotspotList[i].hotspotTitle}}</p>
            <p class="item-date">{{hotspotList[i]&&hotspotList[i].itemcreateat}}</p>
         </div>

資料為對象:
hotspotList.item&&hotspotList.item.itemid
           

原因二:異步問題,在還沒查詢完第一個接口時候,就查詢第二個接口。第二個接口中有用到第一個接口中的内容,是以會報錯。

解決方案

方法一:在調用第一個接口的時候使用,加上async,await
    async getOwnerUnit() {
      await DistAPI.getOwnerUnit().then((res) => {//此處是調用接口
        if (res.code == 200) {
          this.ownerUnitList = res.data
        }
      })
    },
           
方法二:針對異步請求,接口請求順序問題導緻報錯,使用.then()方法
 created() {
    this.getOwnerUnit().then(() => {//請求完第一個接口之後,再請求第二個接口,完美!!
      this.getFormDetail()
    })
  },
           

繼續閱讀