Don’t Use v-if with v-for Elements

Sometimes we use v-if conditionals with v-for to filter our data. It’s super tempting to want to use v-if with v-for in order to filter elements of an array. 

This is very bad practice. Don't do it again. The problem with this is that VueJS prioritizes the v-for directive over the v-if directive. So under the hood, it loops through every element and THEN checks the v-if conditional. 

Read also : Conditionals and Loops | Vue Native

This means that even if we only want to render a few elements from a list, we’ll have to loop through the entire array. Isn't it ? So this can be a smarter solution to avoid such condition. See the below example.

this.items.map(function (item) {
  if (item.price < 500) {
    return item
  }
})

v-if-inside-v-for

Have a look an another solution of that which is a bit different from above example.

This is good for a few reasons.

  • Rendering is much more efficient because we don’t loop over every item
  • The filtered list will only be re-evaluated when a dependency changes
  • It helps separate our component logic from the template, making our component more readable 

Hope it can help you. 

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website