How to use for loop in VueJS?
February 12, 2023Hi Friends đź‘‹,
Welcome To SortoutCode! ❤️
Today, I am going to show you How do you use for loop in VueJS?
Table of Content
- Setup the Vue (Optional)
- Create FirstComponent.vue and import it into App.js
- Use for loop
This article will guide you to how do I use for loop in vueJS.
Setup the Vue (Optional)
First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.
How to Install the VueJS project?
Create FirstComponent.vue and import it into App.js
Create the new component in the src/components/
components folder. the component name is FirstComponent.vue
and imported into the App.js
file:
App.js
<template>
<div id="app">
<FirstComponent />
</div>
</template>
<script>
import FirstComponent from "./components/FirstComponent.vue";
export default {
name: "App",
components: {
FirstComponent,
},
};
</script>
Use for loop
We are going to call API through the fetch
method and use API response and render using the v-for
loop. we are using the v-for
loop render list based on the array. The v-for
directive requires a special syntax in the form of item in items
, where items
is the source data array and item
is an alias for the array element being iterated on. Let’s see the code example:
FirstComponent.js
<template>
<div id="app">
<div style="display: flex; flex-wrap: wrap">
<div v-for="item in listItems" :key="item.id" class="card">
<div class="card-body">
<h6>
<b>Name: {{ item.name }}</b>
</h6>
<p>Email Id: {{ item.email }}</p>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "FirstComponent",
data() {
return {
listItems: [],
};
},
methods: {
async getData() {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
this.listItems = await res.json();
},
},
mounted() {
this.getData();
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
For now, let’s check the output.
All the best 👍.