PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 16, 2022

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

 October 16, 2022     javascript, vue.js, vuejs2     No comments   

Issue

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


Solution

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



Answered By - Boussadjra Brahim
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing