How to check if variable is empty or null with Vue v-if and JavaScript?

Sometimes, we want to check if variable is empty or null with Vue v-if and JavaScript.

In this article, we’ll look at how to check if variable is empty or null with Vue v-if and JavaScript.

How to check if variable is empty or null with Vue v-if and JavaScript?

To check if variable is empty or null with Vue v-if and JavaScript. we can set v-if to the variable we want to check.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and the app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `
    <div>
      <div v-if='archiveNote'>
      	{{archiveNote}}
      </div>
    </div>
  `,
  data: {
    archiveNote: undefined
  },
  mounted() {
    setTimeout(() => {
      this.archiveNote = 'note'
    }, 1000)
  }
})

to check if archiveNote is truthy before we show the div.

In the mounted hook, we set this.archiveNote to 'note' which will make it truthy in the setTimeout callback which will run in 1 second after mounted is run.

Conclusion

To check if variable is empty or null with Vue v-if and JavaScript. we can set v-if to the variable we want to check.