Vue.js is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developer.
In order to repeat a task for a fixed amount of time, we make use of the for loop. The Components are used to build the combination of UI elements that need to be called any number of times. Some data might be component-specific. Those data need to be bound with a component on a repeated basis. This is when v-for list rendering with a component comes in handy. The v-for is used to traverse over the data and display the required component as per the user choice.
Syntax:
<Component v-for="item in items" :key="item.id"> Content </Component>
Approach: Here, we will create a Vue project, and then we will create a different UI that displays components.
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: In this example, we are executing a loop to display all the header components. The heading is passed as a prop to the header component.
Header component: Create a new file Header.vue in the components folder.
Header.vue
<template> <h3> {{ index }}-{{ heading }} </h3> </template> <script> export default { name: "Header" , props: [ "heading" , "index" ], }; </script> |
App.vue
<template> <div id= "app" > <h1 style= "color: green" >neveropen</h1> <h2><u>v- for with a component</u></h2> <Header v- for = "(heading, index) in data" v-bind:heading= "heading" v-bind:index= "index" > </Header> </div> </template> <script> import Header from "./components/Header" ; export default { name: "App" , components: { Header, }, data() { return { data: [ "Header component 1" , "Header component 2" , "Header component 3" , "Header component 4" , "Header component 5" , ], }; }, }; </script> |
Output:
Reference: https://v2.vuejs.org/v2/guide/list.html#v-for-with-a-Component