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

Implement QR code scanning function through Vue

hint This plug-in can only be accessed under the ...

Mysql5.6.36 script compilation, installation and initialization tutorial

Overview This article is a script for automatical...

MySQL 8.0.16 winx64 installation and configuration method graphic tutorial

I just started learning about databases recently....

MySql fuzzy query json keyword retrieval solution example

Table of contents Preface Option 1: Option 2: Opt...

VMware configuration VMnet8 network method steps

Table of contents 1. Introduction 2. Configuratio...

Solve the problem that Mysql5.7.17 fails to install and start under Windows

Install MySQL for the first time on your machine....

HTML+CSS merge table border sample code

When we add borders to table and td tags, double ...

Is a design that complies with design specifications a good design?

In the past few years of my career, I have writte...

Markup language - for

Click here to return to the 123WORDPRESS.COM HTML ...

Pure CSS to achieve the list pull-down effect in the page

You may often see the following effect: That’s ri...

Detailed example of MySQL exchange partition

Detailed example of MySQL exchange partition Pref...

How to modify the default submission method of the form

The default submission method of html is get inste...

Why node.js is not suitable for large projects

Table of contents Preface 1. Application componen...

503 service unavailable error solution explanation

1. When you open the web page, 503 service unavai...