It’s almost impossible to create an app without needing to iterate over an array. For example, if you want to display a list of properties, you’ll likely need to iterate over them. Vue’s v-for directive makes this process seamless and efficient.
Basic Example: Looping Through an Array
Let’s start with a simple scenario: looping through an array of names.
const petNames = ref(['Luna', 'Star', 'Black']);
To display each name, use the v-for directive in your template:
<p v-for="(name, index) in petNames" :key="index"> {{ name }} is at position {{ index + 1 }}</p>
• v-for="(name, index) in names": Loops through the names array, exposing each value as name and its position as index
• :key="index": Ensures efficient DOM updates by providing a unique identifier for each element
• index + 1: Converts the zero-based index to a human-readable count
When rendered, the output will be:
HTML Output 1
Creating Lists with Loops
You can also create lists by wrapping your v-for directive inside <ul> and <li> tags:
<ul> <li v-for="(name, index) in petNames" :key="index"> {{ index + 1 }}. {{ name }} </li></ul>
HTML Output 2
Iterating Through a Collection of Objects
When working with collections, such as an array of objects, you can access specific properties during iteration.
• pet.type and pet.name: Access the type and name properties of each pet object
• :key="index": Helps Vue optimize rendering
Output:
HTML Output 3
Looping Through an Object’s Key-Value Pairs
Sometimes, you may need to iterate over an object’s keys and values instead of an array. Let’s consider an object that represents a user:
const user = ref({ name: 'Tomas', lastName: 'Jones', age: 30,});
Using v-for, you can extract both keys and values:
<ul> <li v-for="(value, key, index) in user" :key="index"> {{ key }}: {{ value }} </li></ul>
(value, key, index) in user: Loops through the object, exposing its values as value, keys as key, and positions as index
Output:
HTML Output 4
Comparison with React or Angular
Compared to other frameworks like React or Angular, Vue.js simplifies iteration by making v-for easy to use and intuitive. Whether working with arrays, collections, or objects, Vue eliminates the need for complex JavaScript functions or third-party utilities.
Conclusion
• Use v-for to loop through arrays, collections, or objects effortlessly
• Always include a :key to ensure efficient DOM updates