Table of Contents
2. The priority of the two" >2. The priority of the two
##3. Precautions" >##3. Precautions
Home Web Front-end Front-end Q&A What is the difference between v-if and v-for in vue

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

Dec 27, 2022 pm 06:48 PM
vue3 v-if v-for

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to refresh partial content of the page in Vue3 How to refresh partial content of the page in Vue3 May 26, 2023 pm 05:31 PM

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

How to select an avatar and crop it in Vue3 How to select an avatar and crop it in Vue3 May 29, 2023 am 10:22 AM

The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

How to use defineCustomElement to define components in Vue3 How to use defineCustomElement to define components in Vue3 May 28, 2023 am 11:29 AM

Using Vue to build custom elements WebComponents is a collective name for a set of web native APIs that allow developers to create reusable custom elements (customelements). The main benefit of custom elements is that they can be used with any framework, even without one. They are ideal when you are targeting end users who may be using a different front-end technology stack, or when you want to decouple the final application from the implementation details of the components it uses. Vue and WebComponents are complementary technologies, and Vue provides excellent support for using and creating custom elements. You can integrate custom elements into existing Vue applications, or use Vue to build

Detailed explanation of v-for function in Vue3: perfect solution to list data rendering Detailed explanation of v-for function in Vue3: perfect solution to list data rendering Jun 18, 2023 am 09:57 AM

With the continuous advancement of digital technology, front-end development has become an increasingly popular profession. Vue3 has become the first choice of more and more developers due to its simplicity, ease of use, efficiency and stability. Among them, the v-for function is one of the core functions used for list data rendering in Vue3. In this article, we will provide a detailed explanation of the v-for function in Vue3, so that you can better use it to solve actual development problems. 1. Basic syntax The basic syntax of the v-for function is as follows: &lt;divv-

Vue error: The v-if directive cannot be used correctly for conditional rendering. How to solve it? Vue error: The v-if directive cannot be used correctly for conditional rendering. How to solve it? Aug 19, 2023 pm 01:09 PM

Vue error: The v-if directive cannot be used correctly for conditional rendering. How to solve it? In Vue development, the v-if directive is often used to render specific content in the page based on conditions. However, sometimes we may encounter a problem. When we use the v-if instruction correctly, we cannot get the expected results and receive an error message. This article will describe a solution to this problem and provide some sample code to aid understanding. 1. Problem Description Usually, we use the v-if directive in the Vue template to determine whether

Best practices and performance optimization methods for using v-for in Vue Best practices and performance optimization methods for using v-for in Vue Jul 17, 2023 am 08:53 AM

Best practices and performance optimization methods for using v-for in Vue Introduction: In Vue development, it is very common to use the v-for instruction, which can conveniently traverse and render the data of an array or object onto the template. However, improper use of v-for may cause performance issues when dealing with large-scale data. This article will introduce the best practices when using the v-for directive and provide some performance optimization methods. Best practice: When using the v-for instruction in Vue to render each item of data using a unique Key value, you need to

Tips for using v-for to implement dynamic sorting in Vue Tips for using v-for to implement dynamic sorting in Vue Jun 25, 2023 am 09:18 AM

Vue is a modern JavaScript framework that helps us build dynamic web pages and complex applications easily. In Vue, you can easily create loop structures using v-for to iteratively render data. In some specific scenarios, we can also use v-for to implement dynamic sorting. This article will introduce how to use v-for to implement dynamic sorting techniques in Vue, as well as some application scenarios and examples. 1. Use v-for to make it simple

See all articles