What is the difference between v-if and v-for in vue
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.
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>
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>
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 } } })
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 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>
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 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 === '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 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>
computed: { items: function() { return this.list.filter(function (item) { return item.isShow }) } }
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>
<ul> <li v-for="item in activeList">{{item.name}}</li> </ul> computed: { activeList() { return this.list.filter(val => { return val.actived; }); } },
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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&

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

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

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: <divv-

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

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
