Why can't v-if and v-for be used together?

Because the official website of vue has a clear statement: v-for has a higher priority than v-if, looping first and then making judgments will cause performance waste, so don't put them on the same element during use.

Second, they work differently:

The essence of v-if is to dynamically create or delete element nodes, and only when the condition is true will the node be created.

v-for is to traverse the array for data rendering, and it is recommended to set the key value. If there is an id, set the id as the key value, and if there is no id, set the index as the key value.

The role of the key value:

The main function of the key value here is to add a unique identifier to the element to improve the rendering performance of vue; when the data changes, vue will use the diff algorithm to compare the old and new virtual DOM, and only consider reuse if the key value is the same Element, if the key value is different, the element will be forced to update; generally by setting the element key value as id, to ensure that vue can maximize the reuse of elements with the same key value when updating data Q: Why can’t the key value be subscripted
? ?

Because when the length of the array changes, other element subscripts will be affected; if the subscript is used as the key value, due to the change of other element subscripts, Vue will think that your key value has also changed, and will update the element. affect performance

solution:

1. Nesting in the outer layer template(page rendering does not generate domnodes), first perform v-if judgment on this layer, and then perform v-for loop inside

<template v-if="isShow">

  <p v-for="item in list">

</template>

2. If the judgment condition appears inside the loop, filter the value that requires v-for in the computed property first

 computed: {

    items: function() {

      return this.list.filter(item => 筛选条件)

    }

  }

3. Use v-if and v-for separately


For details, you can directly view the conditional rendering section of the Vue official website:

Conditional Rendering — Vue.js

Guess you like

Origin blog.csdn.net/weixin_48082900/article/details/128489658