ramjamx
ramjamx

Reputation: 21

VUE 2: Dont use a component if an object is null

I am currently having a problem: I need to use a component only if the source information is available, else don't use it. I have tried with v-if but it appears to call the component anyway.

<div v-if="entry.banners">
   <banner-selector
      v-for="banner in entry.banners"
      :key="banner.id"
      :banner-id="banner.id"
      :autotarget="banner.autotarget" :promo-selected="promoSelected"
      @selectedItem="updateItemSelected($event)" />
    <banner-base
      v-for="banner in entry.banners"
       :key="banner.id"
       :slug-ficha="slugSelected"
       :promo-selected="promoSelected" 
       :banner-id="banner.id" />
</div>

This gives me an error because id doesn't exist when entry.banners is null. Also I am declaring banner-selector and banner-base, but they won't be used when the entry.banners object is null.

Any advice?

Upvotes: 0

Views: 356

Answers (3)

Zeppelin17
Zeppelin17

Reputation: 61

Are you sure is ? is a falsy value, so probably the problem is elsewhere.

Maybe you have some empty banner object that is causing the problem. In this case I would log the the when the component is created and mounted and check what data is inside.

Upvotes: 0

Kamran Shahid
Kamran Shahid

Reputation: 21

just put the below condition in the div:

 v-if="entry && entry.banners && entry.banners.length"

Upvotes: 1

matiaslauriti
matiaslauriti

Reputation: 8082

You can try doing entry.banners !== null, but have in mind that (I have no idea what could happen) if entry.banners is an empty object instead of null.

So other solution could be to create a computed property and do that check inside the computed property (both null or empty) and done.

I am aware that maybe there is a better solution, but these are the solutions I can share with you.

Upvotes: 0

Related Questions