[Vuejs]-Manage undefined value of an object

0πŸ‘

βœ…

The problem is results.object is possibly undefined, so you should verify it exists before trying to access a subproperty. You could do this easily by wrapping both img elements with a <template v-if="results.object">. And you could show a fallback img, using an <img v-else>, adjacent to this template:

<template v-if="results.object">
  <img 
    v-if="results.object.value === 'test'"
    src="@/assets/images/services/img.svg"
    class="w-60"
    alt=""
  />
  <img
    v-else-if="results.object.value === 'test2'"
    src="@/assets/images/services/img2.svg"
    class="w-80"
    alt=""
  />
</template>

<!-- show fallback img if no `results.object` -->
<img
  v-else
  src="@/assets/images/services/test3.svg"
  class="w-80"
  alt=""
/>

0πŸ‘

You can use optional chaining like:

results?.object?.value??'default'==='test'

or

just results?.object?.value === 'test'

 <img
      v-if="results?.object?.value === 'test'"
      src="@/assets/images/services/img.svg"
      class="w-60"
      alt=""
    />

<img
      v-else-if="results?.object?.value === 'test2'"
      src="@/assets/images/services/img2.svg"
      class="w-80"
      alt=""
    />

<img
      v-else-if="!results?.object?.value"
      src="@/assets/images/services/test3.svg"
      class="w-40"
      alt=""
    />

Leave a comment