Detailed explanation of why v-if and v-for in Vue are not recommended to be used together

Detailed explanation of why v-if and v-for in Vue are not recommended to be used together

This article mainly introduces why v-if and v-for are not recommended to be used together? Share with you, the details are as follows:

1. Function

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

The v-for directive renders a list based on an array. The v-for directive requires a special syntax of the form item in items, where items is the source data array or object, and item is an alias for 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, which facilitates the optimization of the diff algorithm.

Both in usage

<Modal v-if="isShow" />
 
<li v-for="item in items" :key="item.id">
  {{ item.label }}
</li>

2. Priority

v-if and v-for are both instructions in the vue template system

When the Vue template is compiled, the instruction system is converted into an executable render function

Example

Write a p tag and use v-if and v-for at the same time

<div id="app">
  <p v-if="isShow" v-for="item in items">
    {{ item.title }}
  </p>
</div>

Create a vue instance to store isShow and items data

const app = new Vue({
 el: "#app",
 data() {
  return {
   items: [
    { title: "foo" },
    { title: "baz" }]
  }
 },
 computed: {
  isShow() {
   return this.items && this.items.length > 0
  }
 }
})

The code of the template instructions will be generated in the render function, and the rendering function can be obtained through app.$options.render

ƒ anonymous() {
 with (this) { return 
  _c('div', { attrs: { "id": "app" } }, 
  _l((items), function (item) 
  { return (isShow) ? _c('p', [_v("\n" + _s(item.title) + "\n")]) : _e() }), 0) }
}

_l is the list rendering function of Vue, and an if judgment will be performed inside the function

Preliminary conclusion: v-for has a higher priority than v-if

Then put v-for and v-if in different tags

<div id="app">
  <template v-if="isShow">
    <p v-for="item in items">{{item.title}}</p>
  </template>
</div>

Then output the render function

ƒ anonymous() {
 with(this){return 
  _c('div',{attrs:{"id":"app"}},
  [(isShow)?[_v("\n"),
  _l((items),function(item){return _c('p',[_v(_s(item.title))])})]:_e()],2)}
}

At this point we can see that when v-for and v-if act on different tags, they first make a judgment and then render the list.

Let's look at the Vue source code again

Source code location: \vue-dev\src\compiler\codegen\index.js

export function genElement (el: ASTElement, state: CodegenState): string {
 if (el.parent) {
  el.pre = el.pre || el.parent.pre
 }
 if (el.staticRoot && !el.staticProcessed) {
  return genStatic(el, state)
 } else if (el.once && !el.onceProcessed) {
  return genOnce(el, state)
 } else if (el.for && !el.forProcessed) {
  return genFor(el, state)
 } else if (el.if && !el.ifProcessed) {
  return genIf(el, state)
 } else if (el.tag === 'template' && !el.slotTarget && !state.pre) {
  return genChildren(el, state) || 'void 0'
 } else if (el.tag === 'slot') {
  return genSlot(el, state)
 } else {
  //component or element
  ...
}

When making an if judgment, v-for is judged before v-if

Final conclusion: v-for has a higher priority than v-if

3. Notes

Never use v-if and v-for on the same element at the same time, which will waste performance (each rendering will loop before conditional judgment)

To avoid this situation, nest template in the outer layer (page rendering does not generate DOM nodes), perform v-if judgment in this layer, and then perform v-for loop inside

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

If the condition appears inside a loop, you can use the computed property to filter out items that do not need to be displayed in advance.

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

References

https://vue3js.cn/docs/zh\

This concludes this article on why v-if and v-for in Vue are not recommended to be used together. For more relevant content about why v-if and v-for are not recommended to be used together, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Comparison of v-if and v-for priorities between vue2 and vue3
  • A brief discussion on how to filter conditions when using v-for and v-if together
  • Vue's attention to the specification of v-if and v-for use tutorial
  • Detailed explanation of Vue's common instructions v-if, v-for, v-show, v-else, v-bind, v-on
  • Solve the problem of using v-if or v-bind:class in v-for
  • Example explanation of vuejs's v-for traversal, v-bind dynamic value change, and v-if judgment
  • Summary of common Vue.js instructions (v-if, v-for, etc.)

<<:  Vue custom component implements two-way binding

>>:  Implementing a simple student information management system based on VUE

Recommend

Summary of Common Letters in Unicode

Most of the earliest computers could only use ASC...

Detailed explanation of Vue's live broadcast function

Recently, the company happened to be doing live b...

Let's talk about the Vue life cycle in detail

Table of contents Preface 1. Life cycle in Vue2 I...

Implementation code of jquery step progress axis plug-in

A jQuery plugin every day - step progress axis st...

Detailed explanation of the lock structure in MySQL

Mysql supports 3 types of lock structures Table-l...

Detailed explanation of Linux system directories sys, tmp, usr, var!

The growth path from a Linux novice to a Linux ma...

CocosCreator ScrollView optimization series: frame loading

Table of contents 1. Introduction 2. Analysis of ...

Detailed steps for porting busybox to build a minimal root file system

Busybox: A Swiss Army knife filled with small com...

The background color or image inside the div container grows as it grows

Copy code The code is as follows: height:auto !im...

Detailed graphic tutorial on installing and uninstalling Tomcat8 on Linux

[ Linux installation of Tomcat8 ] Uninstall Tomca...