Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading