drake035
drake035

Reputation: 2897

How to handle object properties not garanteed to exist within template tags in Vue.js?

Getting fatal error TypeError: Cannot read properties of null (reading 'propThatSometimesDoesNotExist') with following code:

<template>
  <div>
    <img v-if="obj.propThatSometimesDoesNotExist" :src="obj.propThatSometimesDoesNotExist">
  </div>
</template>

Using a computed property instead works fine, but that's not ideal in my particular case (the above is a simplified version of my project).

Can I somehow keep the syntax above while avoiding fatal errors? Perhaps something like optional chaining looking like :src="obj?.propThatSometimesDoesNotExist" (except of course this doesn't work)?

Upvotes: 2

Views: 85

Answers (2)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23490

You can use optional chaining on v-if:

new Vue({
  el: '#demo',
  data() {
    return {
      obj: null
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <img v-if="obj?.propThatSometimesDoesNotExist" :src="obj.propThatSometimesDoesNotExist" />
</div>

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Try the following condition using && operator to ensure that the object is different than null :

 <img v-if="obj && obj.propThatSometimesDoesNotExist" :src="obj.propThatSometimesDoesNotExist">

Knowing that the v-if has the high property when using it with other attributes and directives, so the value checking is done before adding to the src

Upvotes: 1

Related Questions