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

Time:09-15

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)?

CodePudding user response:

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>

CodePudding user response:

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

  • Related