#Summary of the methods of making good use of v-for loop in vue

First, let's introduce the basic usage of v-for official documents

Basic usage of: v-for on the official website

Render elements or template blocks multiple times based on source data. The value of this instruction must use the specific syntax alias in expression to provide an alias for the currently traversed element:

<div v-for="item in items">
  {{ item.text }}
</div>

Alternatively, you can specify an alias for the array index (or a key for the object):

<div v-for="(item, index) in items"></div>
<div v-for="(val, key) in object"></div>
<div v-for="(val, name, index) in object"></div>

The default behavior of v-for attempts to modify elements in place instead of moving them. To force it to reorder elements, you need to provide a sorting prompt with a special attribute key:

<div v-for="item in items" :key="item.id">
  {{ item.text }}
</div>

From 2.6, v-for can also be implemented in Iterative protocol Used on the values of, including native Map and Set. However, it should be noted that Vue 2 X currently does not support responsive Map and Set values, so changes cannot be detected automatically.

When used with v-if, v-for takes precedence over v-if.

The above is the explanation on the official website

Next, let's move on to the topic:

The v-for loop in Vue allows you to write a for loop in template code, especially when we do the following operations:

  • Render array or list
  • Traversal object properties

In the most basic usage, the v-for loop is used as follows:

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

However, it also has some usage you don't know, which can make your v-for code more accurate, and efficient.

1. Always use key in v-for loop

First, we want to discuss a usage that many people already know:
Use the key in the v-for loop.
By setting a unique key attribute, you can ensure that your component works as expected. If we do not use key, vue itself will make the DOM as efficient as possible, which may lead to disordered order or other unpredictable behavior of v-for elements. Can't achieve our ultimate goal.
If we have a unique key reference to each element, we can better predict how the DOM will be manipulated.

  <li   
    v-for='item in items'  
    :key=item.id'    
  >  
    {{ item.name }}  
  </li>  
</ul>

2. Cycle in a range with v-for

Although in most cases v-for is used to iterate through arrays or objects, there are certainly cases where we may only want to iterate a certain number of times. Suppose we want to create a Pagination System in the online store and want to display only 10 items per page. By using variables to track our current page number, we can handle pagination like this:

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

3. Avoid using v-if in the loop

It is very common to mistakenly use v-if to filter data [1] in a v-for loop. Although this seems intuitive, it leads to a huge performance problem - vue's v-for takes precedence over the v-if instruction [2]. This means that your component will traverse each element and then check the v-if condition to see if it should be rendered.

If you use v-if and v-for together, you will traverse every element of the array no matter what your condition is.

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

What problems will the above code cause? Suppose there are thousands of items in our product array, but only 3 products in sales status need to be rendered. Then, every time you re render, vue must traverse thousands of items even if the three products sold have not changed at all. So we should try to avoid this situation. Instead of using v-for and v-if together, there are two alternatives.

4. Use calculated attributes or methods instead

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

  1. Use calculated properties
  2. Use filtering method

As for which way, you has the final say. The two are briefly introduced below. First, you need to set a calculation property. In order to achieve the same effect as using v-if before, the code should be as follows:

  <li v-for='products in productsOnSale' :key='product._id' >  
    {{ product.name }}  
  </li>  
</ul>  
  
// ...  
<script>  
  export default {  
    data () {  
      return {  
        products: []  
      }  
    },  
    computed: {  
      productsOnSale: function () {  
        return this.products.filter(product => product.onSale)  
      }  
    }  
  }  
</script>

This has several advantages:

  1. Data properties are reassessed only when dependencies change
  2. The template will only traverse the goods on sale, not every item

The code of the second method is almost the same as before:

  <li v-for='products in productsOnSale(50))' :key='product._id' >  
    {{ product.name }}  
  </li>  
</ul>  
  
// ...  
  
<script>  
  export default {  
    data () {  
      return {  
        products: []  
      }  
    },  
    methods: {  
      productsOnSale (maxPrice) {  
        return this.products.filter(product => product.onSale && product.price < maxPrice)  
      }  
    }  
  }  
</script>

5. Put the cycle into the packaging element

Sometimes you may want to combine v-for with v-if to determine whether you need to render a list. What if we just want to render the product list when the user logs in.

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

What's wrong with the above code? As before, the vue template prioritizes v-for, so it iterates through each element and checks for v-if** Even if nothing is rendered in the end, thousands of elements will be traversed** The simpler solution is to change the position of the v-if statement of the 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 islogged in is false, there is no need to iterate at all.

6. Access the index in a loop

In addition to traversing the array and accessing each element, you can also track the index of each item. To achieve this, we must add an index value after our project. This is very simple and useful for paging, displaying list indexes, displaying rankings, and so on.

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

7. Iteration object

So far, we've only really studied traversing arrays with v-for. But we can easily iterate over key value pairs of objects. Similar to accessing the index of an element, we must add another value to the loop. If you loop an object with a single parameter, all items will loop. If we add another parameter, we will get item and key. If you add a third, you can also access the index of the v-for loop. Suppose you want to traverse each attribute of the commodity, the code should be as follows:

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

Keywords: Vue

Added by Bidibule on Wed, 29 Dec 2021 20:07:59 +0200