我想檢查是否在專案物件上設定了屬性 url,如果不存在我想顯示占位符影像。像這樣的東西:
<img
v-if="item.relationships.main_image.attributes.url"
:src="item.relationships.main_image.attributes.url"
:alt="item.attributes.name"
class="h-full w-full"
/>
<img v-else :src="require('@/assets/placeholder.png')" alt=""/>
問題是我的專案物件可能沒有任何屬性,因為后端僅在實際存在鏈接到該專案的影像時才發送這些屬性。
我如何檢查一個物件是否具有那么深的屬性?
Error given: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'attributes')
uj5u.com熱心網友回復:
您可以簡化這一點并擺脫這個額外的 img 標簽。此外,如果任何專案物件屬性可以是null您可以使用可選鏈接(例如item?.relationships...)。
我不知道哪個屬性 can 和 cannot be null,所以讓我們假設最壞的情況:
<img :src="item?.relationships?.main_image?.attributes?.url || require('@/assets/placeholder.png')"
:alt="item?.attributes?.name || 'placeholder'"
class="h-full w-full"/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/467267.html
下一篇:單擊時將活動類添加到導航欄元素
