VueJs v-if

v-if directive adds or removes DOM elements based on the given expression.We can use the show property from the data model and show a Hello World in the view.

<!DOCTYPE html>
<html lang="en">
<head>
   <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
     <div id="app">
	     <div v-if="show">Hello World!</div>
     </div>
     <script>
     new Vue ({
        	el: '#app',
		data: {
		        show: false
		}
             })
   </script>
 </body>
</html>

Now, the "Hello World" will not show because show is set to false. Setting the data.show value to true would add the Hello World to the DOM.

Output

<!DOCTYPE html>
<html lang="en">
<head>
   <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
     <div id="app1">
       <div v-if="show">Hello World!</div>
     </div>
     <script>
     new Vue ({
          el: '#app1',
    data: {
            show: true
    }
             })
   </script>
 </body>
</html>

Output

difference between the v-show and v-if

  • v-if - Only renders the element to the DOM if the expression passes.
  • v-show - Renders all elements to the DOM and then uses the CSS display property to hide elements if the expression fails.
  • v-show - Does not support v-else, v-else-if