7 Ways to Write a Vue v-for Loop

7 Ways to Write a Vue v-for Loop

This is particularly useful in situations such as:

  • Rendering an array or list
  • Iterating over object properties

The most basic usage of the v-for loop in Vue is this:

<ul>
  <li v-for='product in products'>
    {{ product.name }}
  </li>
</ul>


However, in this article, we’ll look at some awesome ways to make your v-for code more precise, predictable, and efficient.

Let’s get started.

1. Always use key in v-for loops

First, we discuss a common best practice that most Vue developers already know — using :key in a v-for loop. By setting a unique key property, you can ensure that the component works as expected.

If we don't use :key , Vue will make the DOM as efficient as possible. This may cause v-for elements to appear out of order or otherwise behave in an unpredictable way.

If we have a unique key reference to each element, then we can more predictably manipulate the DOM.

<ul>
  <li 
    v-for='product in products'
    :key='product._id'  
  >
    {{ product.name }}
  </li>
</ul>


2. Use v-for loop within a certain scope

While most of the time v-for is used to loop over arrays or objects, there are also cases where we only want to iterate a specific number of times.

For example, let's say we're creating a pagination system for an online store, and we only want to display 10 products per page. Using a variable to keep track of the current page number, you can handle paging like this.

<ul>
  <li v-for='index in 10' :key='index'>
    {{ products[page * 10 + index] }}
  </li>
</ul>


3. Avoid using v-if in loops

A super common mistake is using v-if to filter data in v-for loop.

While this may seem intuitive, it can lead to a huge performance issue — VueJS will prioritize v-for over v-if directives.

This means that the component will iterate over each element before checking the v-if condition to see if it should be rendered.

If you use v-if with v-for, it will iterate over every item in the array, no matter what the condition is.

// Bad practice!
<ul>
  <li 
    v-for='product in products' 
    :key='product._id' 
    v-if='product.onSale'
  >
    {{ product.name }}
  </li>
</ul>


So what is the problem?

Suppose products array has thousands of items, but you only want to render the 3 products that are currently on sale.

On every re-render, Vue has to iterate through those thousands of items, even though the 3 products being sold haven't changed at all.

You must try to avoid using v-if and v-for together.

Next, two alternative approaches are described.

4. Use computed properties or methods

To avoid the above problems, we should filter the data before iterating it in the template. There are two very similar ways to do it:

  • Using computed properties
  • Use filter method

It’s up to you to choose, but let’s quickly cover both methods.

First, we just need to set up a computed property. To get the same functionality as the previous v-if, the code would look like this.

<template>
  <ul>
    <li v-for="products in productsOnSale" :key="product._id">
      {{ product.name }}
    </li>
  </ul>
</template>

<script>
  export default {
    data () {
      return {
        products: []
      }
    },
    computed: {
      productsOnSale: function () {
        return this.products.filter(product => product.onSale)
      }
    }
  }
</script>

The benefits are:

  • Data properties are only re-evaluated when dependencies change
  • The template only iterates over the products on sale, not every product

The code for using the filter method is almost the same, but using the filter method changes the way you access the value inside the template. However, if we want to be able to pass variables to the filtering process, then we should choose the method route.

<template>
  <ul>
    <li v-for="products in productsOnSale(50))" :key="product._id">
      {{ product.name }}
    </li>
  </ul>
</template>

<script>
  export default {
   data () {
    return {
     products: []
    }
   },
   methods: {
    productsOnSale (maxPrice) {
     return this.products.filter(product => product.onSale && product.price < maxPrice)
    }
   }
  }
</script>


5. Or wrap a layer of elements around the loop

You may still want to combine v-for with v-if when deciding whether to render the list at all.

For example, what if we only want to render a list of products when the user is logged in.

Error code:

<ul>
  <li 
    v-for='product in products' 
    :key='product._id' 
    v-if='isLoggedIn' <!-- HERE -->
  >
    {{ product.name }}
  </li>
</ul>


What's wrong with this?

Same as before. The Vue template will take v-for into account - so it will loop over each element and check v-if .

This will loop over thousands of elements even if nothing is rendered in the end.

For this example, a simple solution is to move the v-if statement.

Better code!

<ul v-if='isLoggedIn'> <!-- Much better -->
  <li 
    v-for='product in products' 
    :key='product._id' 
  >
    {{ product.name }}
  </li>
</ul>


This is much better, because if isLoggedIn is false — then no iteration is needed at all.

6. Accessing indexes in loops

Instead of iterating over the array and accessing each element, we can also keep track of the index of each item.

To do this, we need to add an index value after the item. This is super simple, but can be useful for paging, showing list index, showing rankings, etc.

<ul>
  <li v-for='(products, index) in products' :key='product._id' >
    Product #{{ index }}: {{ product.name }}
  </li>
</ul>


7. Iteration Objects

So far, we have only looked at using v-for to iterate over an array. But we can also easily learn to iterate over the key-value pairs of an object.

Similar to accessing the index of an element, we need to add another value to the loop. If we loop over an object with a single argument, we will loop over all items.

If we add another parameter, we get the item and the key. If we add a third argument, we can also access the index of the v-for loop.

Suppose we want to iterate over every attribute in a product. Then the code is as follows:

<ul>
  <li v-for='(products, index) in products' :key='product._id' >
    <span v-for='(item, key, index) in product' :key='key'>
      {{ item }}
    </span>
  </li>
</ul>


in conclusion:
Hopefully this post helped you learn some best practices for using the Vue v-for directive.

This concludes this article on 7 ways to write Vue v-for loops. For more information about Vue v-for loops, please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use v-for loop to generate dynamic tags in Vue.js
  • Attributes in vue v-for loop object
  • Implementing circular scrolling list function based on Vue
  • Detailed explanation of the loop form item example in Vue
  • An example of implementing a simple infinite loop scrolling animation in Vue
  • This article will show you the event loop mechanism of vue.js

<<:  MySQL process control IF(), IFNULL(), NULLIF(), ISNULL() functions

>>:  Using CSS3 to create header animation effects

Recommend

Rendering Function & JSX Details

Table of contents 1. Basics 2. Nodes, trees, and ...

Solution to inconsistent display of cursor size in input box

The cursor size in the input box is inconsistent T...

Detailed explanation of Vue component reuse and expansion

Table of contents Overview Is the extension neces...

How to use Linux whatis command

01. Command Overview The whatis command searches ...

Detailed installation and configuration of Subversion (SVN) under Ubuntu

If you are a software developer, you must be fami...

Using JS timer to move elements

Use JS timer to make an element to make a method ...

Detailed explanation of how to solve the problem of too long content in CSS

When we write CSS, we sometimes forget about the ...

Summary of common functions of PostgreSQL regular expressions

Summary of common functions of PostgreSQL regular...

CSS3 uses var() and calc() functions to achieve animation effects

Preview knowledge points. Animation Frames Backgr...

Solution to CSS flex-basis text overflow problem

The insignificant flex-basis has caused a lot of ...

Vue uses openlayers to load Tiandi Map and Amap

Table of contents 1. World Map 1. Install openlay...

Use of MySQL SHOW STATUS statement

To do MySQL performance adjustment and service st...

Detailed explanation of HTML document types

Mine is: <!DOCTYPE html> Blog Garden: <!...