Which one has higher priority, v-if or v-for in vue?

priority

In fact, the answers in vue2 and vue3 are completely opposite.

  • In vue2, v-for has higher priority than v-if
  • In vue3, v-if has higher priority than v-for

The v-if directive is used to render a piece of content conditionally. Directives are used to conditionally render a block of content. This content will only be rendered if the directive's expression returns true.

The v-for directive renders a list based on an array. The v-for directive requires special syntax in the form of item in items, where items is the source data array or object, and item is the alias of the array element being iterated.

When using v-for, it is recommended to set the key value and ensure that each key value is unique. This is the diff algorithm for optimization.

Precautions

Never use v-if and v-for on the same element at the same time, which will cause a waste of performance (each rendering will loop first and then perform conditional judgment)

If you want to avoid this situation, nest the template in the outer layer (page rendering does not generate dom nodes), perform v-if judgment at this layer, and then perform v-for loop internally

<template v-if="isShow">
    <p v-for="item in items">
</template>

If the condition appears inside the loop, you can filter out items that do not need to be displayed in advance through the calculated attribute.

computed: {
    items: function() {
      return this.list.filter(function (item) {
        return item.isShow
      })
    }
}

Guess you like

Origin blog.csdn.net/shanghai597/article/details/131832101