Javascript is required
ยท
6 min read

Unlocking the Power of v-for Loops in Vue With These Useful Tips

Unlocking the Power of v-for Loops in Vue With These Useful Tips Image

Looping through arrays and objects is a common task in Vue applications. The v-for directive is the perfect tool for this job. It is mighty, and you can use it in many different ways. In this article, I will show you some valuable tips and tricks to get the most out of the v-for directive.

Use correct delimiter

The v-for directive supports two different delimiters: in and of. The in delimiter is the default one.

I prefer to use the of delimiter for arrays because it is closer to JavaScript's syntax for iterators like in the for...of loop:

Component.vue
1<script setup lang="ts">
2import { ref } from 'vue'
3
4const items = ref([
5  { id: 'a-1', name: 'Apple' },
6  { id: 'b-1', name: 'Mango' },
7  { id: 'c-1', name: 'Banana' },
8])
9</script>
10
11<template>
12  <ul>
13    <li v-for="item of items">
14      {{ item.name }}
15    </li>
16  </ul>
17</template>

If I want to loop through an object, I use the in delimiter because it is closer to JavaScript's syntax for iterating over object properties:

Component.vue
1<script setup>
2import { ref } from 'vue'
3
4const myObject = ref({
5  title: 'How to do lists in Vue',
6  author: 'Jane Doe',
7  publishedAt: '2016-04-10',
8})
9</script>
10
11<template>
12  <ul>
13    <li v-for="(value, key) in myObject">
14      Key: "{{ key }}", Value: "{{ value }}"
15    </li>
16  </ul>
17</template>

Destructuring objects

It's possible to destructure the current item in the loop, which is useful if you want to access the current item's properties directly:

Component.vue
1<script setup>
2import { ref } from 'vue'
3
4const items = ref([
5  { id: 'a-1', name: 'Apple' },
6  { id: 'b-1', name: 'Mango' },
7  { id: 'c-1', name: 'Banana' },
8])
9</script>
10
11<template>
12  <ul>
13    <li v-for="{ name } in items">
14      Title: {{ name }}
15    </li>
16  </ul>