Skip to content
Advertisement

Vue v-if statement to check if variable is empty or null

I am trying to use a v-if statement to show some HTML only if the archiveNote variable is not empty/null.

JavaScript

Here is how it’s instantiated

JavaScript

which is then passed in from this other Vue file

JavaScript

The block of HTML still shows when archiveNote is console.log out as empty

Advertisement

Answer

If you want to show the <div> only when it is truthy (not empty/null/etc.), you can simply do:

JavaScript

This gives the same result as the double bang:

JavaScript

Both of these expressions evaluate all 8 of JavaScript’s falsy values to false:

  • false
  • null
  • undefined
  • 0
  • -0
  • NaN
  • ''
  • 0n (BigInt)

and everything else to true. So if your variable evaluates to anything but these it will be truthy, and the v-if will show.

Here’s a demo of these and some truthy examples:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement