In VueJS, the V-for loop is something that every project uses, allowing you to write for loops in template code.

In the most basic usage, their usage is as follows.

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

However, in this article, I present six ways to make your V-for code more precise, predictable, and powerful.

Let’s get started.

1. Always use key in v-for loops

First, we’ll discuss a common best practice that most Vue developers already know — using :key in v-for loops. By setting a unique key property, it ensures that the component works the way you expect it to.

If we don’t use keys, Vue will try to make the DOM as efficient as possible, which might mean that the V-for element could be out of order or otherwise behave unpredictably. If we have a unique key reference for each element, we can better predict exactly how the DOM will behave.

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

2. Cycle in a circle

Although most of the time v-for is used to iterate over a set of numbers or objects, in some cases we definitely only want the loop to execute 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 a variable to keep track of the current page number, we can handle paging like this.

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

3. Do not use V-if in loops

A super common mistake is to use V-if to filter data for v-for loops. Although this may seem intuitive, it can cause a huge performance problem — VueJS prioritizes v-for over V-IF instructions.

This means that your component will loop through each element and then check the V-IF condition to determine if it should be rendered. So, in effect, no matter what the condition is, you will iterate over each item in the group.

Don’t do this:

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

4. Use computed properties or methods instead

To avoid these problems, we should filter the data in the template before iterating through it. There are two very similar approaches:

  • Using computed properties
  • Use of filtering methods

Let’s take a quick look at both methods.

First, we only need to set a calculation property, and to get the same functionality as the previous V-if, the code should look like this.

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

// ...
<script>
  export default {
    data () {
      return {
        products: []
      }
    },
    computed: {
      productsUnderFifty: function () {
        return this.products.filter(product => product.price < 50)
      }
    }
  }
</script>
Copy the code

The following code is almost identical, but using methods changes the way we access values in the template, which is the best choice if we want to be able to pass variables to filters.

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

// ...

<script>
  export default {
    data () {
      return {
        products: []
      }
    },
    methods: {
      productsUnderPrice (price) {
        return this.products.filter(product => product.price < price)
      }
    }
  }
</script>
Copy the code

5. Access the index of the project in a 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 have to add an index value after the item, which is very simple and can be used for pagination, display list indexes, display rankings, and so on.

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

6. Iterate over an object

So far, we’ve only really seen traversing arrays using V-for, but we can easily traverse an object’s key-value pairs.

Similar to accessing the index of an element, we must add another value to the loop. If we iterate over an object with one argument, we iterate over all the items.

If we add another parameter, we get items and key, and if we add a third, we also have access to the index of the V-for loop.

Suppose we want to traverse every media resource in the product.

<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 short article has taught you some best practices for using Vue’s V-for directive.

Do you have any other suggestions?

Related: 12 Tips and Tricks to Make You a Better Vue.js developer


Original text: learnvue co / 2020/02/6 – t… Translation: Dunib

If you have inspiration and help, you can click a concern, collection, also can leave a message to discuss, this is the biggest encouragement to the author.

About the author: Web front-end engineer, full stack development engineer, continuous learner.

Now pay attention to “front-end foreign language selection” wechat public number, but also send a network of high-quality video courses network disk information ah, can save you a lot of money!