How to Loop X Times with v-for in VueJS?
Last Updated :
11 Sep, 2024
Vue.js is a progressive JavaScript framework widely used for building user interfaces. One of its core features is the v-for directive, which allows you to iterate over data or render a block of elements a specified number of times. we will explore various ways to loop X times using v-for in Vue.js. This includes setting up a Vue.js application, running the code, and viewing the output.
The v-for directive in Vue.js is used to render a list of items or iterate a specific number of times in the DOM. If you need to loop a set number of times (X times), there are multiple ways to achieve this. Vue.js allows you to loop through arrays or generate ranges dynamically.
These are the following approaches:
Steps to Create the Vue.js Application
Step 1: Install Vue CLI
- First, you need to install Vue CLI if you don’t have it already
npm install -g @vue/cli
Step 2: Create a Vue.js Project
- Run the following command to create a new Vue.js project
vue create v-for-loop-demo
- Select the default options or customize them according to your project needs. Once the project is created, navigate to the project folder
cd v-for-loop-demo
Step 3: Run the Development Server
- Start the development server to serve your project locally
npm run serve
Project Structure:
Project StructureUpdated Dependencies:
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0"
},
- Make sure to update the dependencies if required by running
npm install
Using an Array of Length X
The simplest way to loop X times is to create an array of the required length and use v-for to iterate over it. You can create an empty array with the desired number of elements and loop through it using v-for.
Syntax:
<div v-for="n in X" :key="n">
<!-- Loop content -->
</div>
Example: This example shows the use of an Array to show the iteration.
JavaScript
// App.vue
<template>
<div>
<div v-for="n in 5" :key="n">Loop iteration: {{ n }}</div>
</div>
</template>
<script>
export default {
data() {
return {
X: 5,
};
},
};
</script>
Output:
OutputUsing Array Constructor to Create a Range
Another approach is to use the Array constructor to directly create an array of a specific length and populate it with values using map or keys().
Syntax:
<div v-for="n in Array.from({ length: X }, (_, i) => i + 1)" :key="n">
<!-- Loop content -->
</div>
Example: This example shows the use of Array Constructor to Create a Range.
JavaScript
// App.vue
<template>
<div>
<div v-for="n in Array.from({ length: 5 }, (_, i) => i + 1)" :key="n">
Loop iteration: {{ n }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
X: 5,
};
},
};
</script>
Output:
Output