Vue.js is one of the best frameworks for JavaScript like React JS. The Vue JS is used to design the user interface layer, it is easy to pick up for any developer. It is compatible with other libraries and extensions as well.
In order to repeat a task for a fixed amount of time, we make use of the for loop. There are a lot of data that needs to be rendered on a web page. Sometimes the user requires the data to be shown on a certain condition. This is when v-if comes in handy. It runs the loop only if a certain condition is true. Based on the Boolean value the UI response is set. This comes under the part of “Vue JS Conditional Rendering“.
Syntax:
<ul v-if="condition" > <li v-for="condition"> Content ....... <li> </ul>
Approach: Here, we will create a Vue project, and then we will create a different UI that uses v-if.
Creating Vue Project:
Step 1: To create a Vue app you need to install Vue modules using this npm command. You need to make sure you have the node installed previously.
npm install vue
Step 2: Use Vue JS through CLI. Open your terminal or command prompt and run the below command.
npm install --global vue-cli
Step 3: Run the below command to create the project.
vue init webpack myproject
Step 4: After creating your Vue project move into the folder to perform different operations.
cd myproject
Step to run the application: Open the terminal and type the following command.
npm run dev
Open your browser. Open a tab with localhost running (http://localhost:8080/) and you can see the output shown in the image.
Project Structure: After running the commands (mentioned in the above steps), if you open the project in an editor, you can see a similar project structure (as shown below).
Example: Running a loop to display a list of string values. The loop will only run if the print value is true. A condition is set using the v-if.
App.vue
<template> <div id= "app" > <h1 style= "color: green" > neveropen </h1> <ul v- if = "print" > <h3>v- if set to true </h3> <strong> Print all element in list </strong> <li v- for = "(structure, index) in data_structures" :key= "index" > <strong> {{ structure }} </strong> </li> </ul> <ul v- if = "!print" > <h3>v- if set to false </h3> </ul> </div> </template> <script> export default { name: "App" , data() { return { print: true , data_structures: [ "Array" , "Linked-list" , "Stack" , "Queue" , "Heap" , "Tree" , ], }; }, }; </script> |
Output: You can see the output for both cases.
- When the print variable is set to true:
- When the print variable is set to false:
Reference: https://v2.vuejs.org/v2/guide/list.html#v-for-with-v-if