The v-if directive is a Vue.js directive used to toggle the display CSS property of a element with a condition. If the condition is true it will make it visible else it will make it invisible. First, we will create a div element with id as app and let’s apply the v-if directive to this element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value.
Syntax:
v-if="data"
Parameters: This directive accepts a single parameter which is the data or a condition.
Example 1: This example uses VueJS to show an element with v-if.
HTML
<!DOCTYPE html> <html> <head> <title> VueJS | v-if directive </title> <!-- Load Vuejs --> <script src= </script> </head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> neveropen </h1> <b> VueJS | v-if directive </b> </div> <div id="canvas" style="border:1px solid #000000; width: 600px;height: 200px;"> <div id="app"> <h2 v-if="message"> This if condition is executed </h2> </div> </div> <script> var app = new Vue({ el: '#app', data: { message: true } }) </script> </body> </html> |
Output:
Example 2: This example uses VueJS to show an element with v-if arithmetic conditions.
HTML
<!DOCTYPE html> <html> <head> <title> VueJS | v-if directive </title> <!-- Load Vuejs --> <script src= </script> </head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> neveropen </h1> <b> VueJS | v-if directive </b> </div> <div id="canvas" style="border:1px solid #000000; width: 600px;height: 200px;"> <div id="app"> <h2 v-if="a > 10">a is greater than 10</h2> <h2 v-if="a < 10">a is smaller than 10</h2> <h2 v-if="a == 10">a is equal to 10</h2> </div> </div> <script> var app = new Vue({ el: '#app', data: { a: 9 } }) </script> </body> </html> |
Output:

