In Vue, the V-for loop is used for almost every project. They allow you to write for loops in template code.

This is especially useful in situations such as:

  • Render an array or list
  • Iterate over object properties

The most basic use of the V-for loop in Vue looks like this:

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

However, in this article, we’ll show you 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 discussed a common best practice that most Vue developers already know — using :key in v-for loops. By setting unique key properties, you can ensure that the component works as expected.

If we don’t use :key, Vue will make DOM as efficient as possible. This can cause the V-for elements to behave out of order or in other unpredictable ways.

If we have a unique key reference for each element, we can better predict how to manipulate the DOM.

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

2. Use v-for loops within limits

While most of the time V-for is used to loop through arrays or objects, there are cases where we just want to iterate a certain number of times.

For example, suppose we are creating a paging system for our online store, and we only want to show 10 products per page. Using variables to track the current page number can handle paging like this.

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

3. Avoid v-if in loops

An extremely common mistake is to use V-if to filter data for v-for loops.

While intuitive, this can lead to a huge performance problem — VueJS will take v-for precedence over v-IF instructions.

This means that the component will iterate over each element and then check the V-IF condition to see if it should be rendered.

If you use v-if with V-for, every term in the array will be iterated, regardless of the condition.

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

So what’s the problem?

Suppose the Products array has thousands of items, but only three selling products that you want to render.

Every time you re-render, Vue has to iterate through thousands of items, even if the three products for sale haven’t changed at all.

The combination of V-if and V-for must be avoided.

Here are two alternatives.

4. Use computed properties or methods

To avoid these problems, we should filter the data before iterating through the template. There are two very similar ways to do this:

  • usecomputedattribute
  • Use of filtering methods

Take your pick. Let’s take a quick look at these two methods.

First, we just need to set up a computed property. To get the same functionality as the previous V-if, the code looks 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>
Copy the code

The benefits are:

  1. Data attributes are only reevaluated when a dependency changes
  2. The template traverses only the products being sold, not every product

The code for using the filter method is almost identical, but using the method changes how values are accessed within the template. However, if we want to be able to pass variables to the filtering process, we should go 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>
Copy the code

5. Or outsource a layer of elements in the loop

When deciding whether to render the list completely, you may still want to combine v-for with V-if.

For example, what if we just want to render the list of products when the user logs in.

Error code:

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

What’s wrong with that?

Same as before. Vue templates prioritize V-for — so they iterate over each element and check for V-IF.

Thousands of elements will loop through even if nothing is rendered at the end.

A simple solution for this example 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>Copy the code

This is much better, because if isLoggedIn is false — there is no need to iterate at all.

6. Access the index in the loop

In addition to walking through groups of numbers and accessing each element, we can also track the index of each item.

To do this, we need to add an index value after the project. This is super simple, but useful for pagination, displaying list indexes, displaying rankings, and so on.

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

7. Iterate over objects

So far, we have only investigated traversing groups using V-for. But we can also easily learn to iterate over an object’s key-value pairs.

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 loop over all items.

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

Suppose we want to iterate over every property in the product. 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>
Copy the code

conclusion

Hopefully this article has helped you learn some best practices for using the Vue V-for directive.

Thanks for reading and happy coding!