1. 程式人生 > 其它 >解決 “TypeError: Cannot read properties of undefined (reading ‘xxx‘)“

解決 “TypeError: Cannot read properties of undefined (reading ‘xxx‘)“

//這個報錯 我的問題是 要用到的資料讀不到這個屬性(我用的vue)
//1.檢查你的data定義的屬性是不是沒有你用到的這個屬性,沒有的話就定義一個,如下:
#template
<div class="he-info__item">
    <span class="he-label">收貨人姓名:</span>
    <span class="he-value">{{ detail.buyer.name }}</span>
</div>
<div class="he-info__item">
   <span class="he-label">聯絡方式:</span>
   <span class="he-value">{{ detail.buyer.mobile }}</span>
</div>

#js
export default {
   data () {
       detail: {
        buyer: {
          name: "",
          mobile: "",
        },
        user: {
          nickname: "",
        },
      },
   }
}
//2.也可能是後端返回給你的資料沒有這個屬性 或者 返回的有的有資料 有的是 null ,
// 這時候就不能寫 {{ item.xxx || “” }} 不然會報錯 Cannot read properties of undefined (reading ‘xxx‘)“ 可以這麼解決 如下:
#template
 <div v-if="!!item.invite">{{ item.invite.nickname }}</div> //有這個屬性才顯示   
 //或者這樣也行
 <div v-if="item?.invite">{{ item.invite.nickname }}</div> //有這個屬性才顯示


 <div v-else>{{ "" }}</div> //沒有返回 或者 null 直接填 “”


//3.網上還有一種就是 檢視未更新 資料還沒返回 你就開始使用這個屬性 可以加個 this.$nectTick (()=>{//獲取資料}) 包裹一下,但是本人沒試過



//完結 撒花 
//僅代表我遇到此問題的解決方法 可能還有別的情況。。。。。。。。。