What is the difference between v-if and v-for in vue

青灯夜游
Release: 2022-12-27 18:48:33
Original
3063 people have browsed it

The difference between v-if and v-for: 1. Different functions. The v-if instruction is used to conditionally render a piece of content. This piece of content will only be rendered when the expression of the instruction returns a true value. Rendering; the v-for directive renders a list based on an array. 2. The priorities are different. v-for has a higher priority than v-if. When judging if, v-for is judged before v-if.

What is the difference between v-if and v-for in vue

The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.

First of all, it is clearly stated in the official documentation that v-for and v-if are not recommended to be used together.

1. The role of v-if and v-for

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

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

In 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.

The difference in usage between the two is as follows:

<div v-if="isShow" >123</div>
  
<li v-for="item in items" :key="item.id">
  {{ item.label }}
</li>
Copy after login

2. The priority of the two

In In use, v-for has a higher priority than v-if

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

When vue template is compiled, Will convert the command system into an executable render function

Example
Write a p tag and use v-if and v-for

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

to create vue Instance, the code for storing 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
  }
 }
})
Copy after login

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(&#39;div&#39;, { attrs: { "id": "app" } }, 
  _l((items), function (item) { return (isShow) ? _c(&#39;p&#39;, [_v("\n" + _s(item.title) + "\n")]) : _e() }), 0) }
}
Copy after login

_l is a list rendering of vue function, an if judgment will be performed inside the function
The initial conclusion is that v-for has a higher priority than v-if

Then v-for and v-if are placed in different labels

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

Then output the render function

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

At this time we can see that when v-for and v-if act on different tags, they are judged first and then the list is rendered

Let’s check 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 === &#39;template&#39; && !el.slotTarget && !state.pre) {
  return genChildren(el, state) || &#39;void 0&#39;
 } else if (el.tag === &#39;slot&#39;) {
  return genSlot(el, state)
 } else {
  // component or element
  ...
}
Copy after login

When making if judgment, v-for is better than v- If is judged first

The final judgment result is that v-for has a higher priority than v-if

##3. 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 avoid this In this case, the template is nested in the outer layer (page rendering does not generate dom nodes), v-if judgment is performed at this layer, and then v-for loop is performed internally

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

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
   })
  }
}
Copy after login

Case description:

Reason: v-for has a higher priority than v-if. The entire array needs to be traversed each time, causing unnecessary calculations and affecting performance.

For example, use v-for to loop 100 li tags on the page, but only display the content of the li tag with index=97. All the rest are hidden.

Even if only one data needs to be used in 100 lists, it will loop through the entire array.

 <ul>
    <li v-for="item in list" v-if="item.actived">{{item.name}}</li>
 </ul>
Copy after login

Solution: Use computed

<ul>
    <li v-for="item in activeList">{{item.name}}</li>
</ul>

computed: {
  activeList() {
    return this.list.filter(val => {
      return val.actived;
    });
  }
},
Copy after login
[Related recommendations:

vuejs video tutorial, web front-end development]

The above is the detailed content of What is the difference between v-if and v-for in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!