Table of Contents
Conclusion
Actual example
source code
Home Web Front-end Vue.js Priority comparison: Which is higher, v-for or v-if?

Priority comparison: Which is higher, v-for or v-if?

Aug 29, 2022 pm 07:52 PM
vue v-if v-for

Which one has higher priority, v-for or v-if? The following article will explain the priorities of v-for and v-if from actual examples and source code. I believe you will be enlightened after reading this.

Priority comparison: Which is higher, v-for or v-if?

Conclusion

1. It is not recommended to use v-for and v-if at the same time. (Learning video sharing: vue video tutorial)

2. v-for in vue2 has a higher priority than v-if. Because vue2 will process v-for first and then v-if when compiling the template, the generated rendering function will first execute the loop, and then execute the conditional judgment inside the loop.

3. The problem caused by doing this is

For scenario 1:<li v-for="user in users" v-if="user.show"&gt ;

Every time we re-render, we have to re-traverse the entire list. In fact, we only need part of the list, which wastes performance. The recommended approach is to filter out the parts we need through calculated attributes and then render them, which is more efficient.

For scenario 2: <li v-for="user in users" v-if="globalShow">

globalShow This judgment actually if it is false , the loop does not need to be executed, but now it is used with v-if, and the loop must be executed regardless of whether globalShow is true or not, which is a complete waste. The recommended approach is to move v-if up to the ul container.

4. It should be noted that for the breaking change of vue3, v-if has a higher priority than v-for in vue3, so if they are used at the same time, for scenario 1, the user has not yet v at this time. -if="user.show" will report an error

5. Generally, if we use eslint, it will also report an error to us. The corresponding rule is: vue/no-use-v-if-with-v- for

Actual example

For example: the following template will generate the following rendering function

<ul>
    <li v-for="user in users" v-if="user.isActive" :key="user.id">
        {{ user.name }}
    </li>
</ul>
Copy after login

The generated rendering function is as follows

with(this) {
    return _c('ul', _l((users), function (user) {
        return (user.isActive) ? _c('li', user.name) : _e()
    }), 0)
}
Copy after login

Generated from above It can be seen from the rendering function that _l will be executed first to traverse user, and conditional judgment will be made inside

source code

processing v-if and v -For's source code

src/compiler/index.js

// 模板解析,生成ast树
const ast = parse(template.trim(), options)
if (options.optimize !== false) {
    optimize(ast, options)
}
const code = generate(ast, options)
Copy after login

Generate code based on ast. If it is the above template, the generated ast is simplified as follows

// 可以看出v-for和v-if都解析出来了
 ast = {
     'type': 1,
     'tag': 'ul',
     'attrsList': [],
     'attrsMap': {},
     'children': [{
     'type': 1,
     'tag': 'li',
     'attrsList': [],
     'attrsMap': {
         'v-for': 'user in users',
         'v-if': 'user.show'
     },
     // v-if解析出来的属性
     'if': 'user.show',
     'ifConditions': [{
         'exp': 'user.show',
         'block': // 指向el自身
     }],
     // v-for解析出来的属性
     'for': 'users',
     'alias': 'user',
     'iterator1': 'index',
     'parent': // 指向其父节点
     'children': [
         'type': 2,
         'expression': '_s(user)'
         'text': '{{user}}',
         'tokens': [
             {'@binding':'user'},
         ]
      ]
     }]
 }
Copy after login

compiler/codegen/index.js

// generate 调用 genElement
const code = ast ? genElement(ast, state) : '_c("div")'
// genElement里面的处理
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el, state)
} else if (el.once && !el.onceProcessed) {
return genOnce(el, state)
// 从这可以看出来,先执行genFor,处理v-for指令,在genFor里面会递归调用genElement,继续处理v-if,genFor会将forProcessed设为true,这样下次进来的时候就不会处理for了
} 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 {
// 最后这里处理标签等
const children = el.inlineTemplate ? null : genChildren(el, state, true)
code = `_c('${el.tag}'${
data ? `,${data}` : '' // data
}${
children ? `,${children}` : '' // children
})`
}

// genFor的代码
const exp = el.for // 对应上面ast的 for: users
const alias = el.alias // alias: user
// iterator1 对应v-for的(item,key,index) in items的key
// iterator2 对应的是index
// 通常我们遍历数组 key就是index
// 假如我们遍历的是对象 key就是对象的key,index就是遍历的索引
const iterator1 = el.iterator1 ? `,${el.iterator1}` : ''
const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''
el.forProcessed = true // 下次递归调用genElement的时候就不会重复处理v-for了
return `${altHelper || '_l'}((${exp}),` +
`function(${alias}${iterator1}${iterator2}){`

// 这里处理完了v-for,递归调用genElement继续处理v-if
`return ${(altGen || genElement)(el, state)}` +
'})'
Copy after login

will eventually generate code similar to the following and return it

_l((users), function(user, index) {
    // 如果有v-if 前面就会有个条件判断,如user.isActive
    return (user.isActive) ? _c('li', user.name) : _e()
});
Copy after login

(Learning video sharing : Web front-end development, Basic programming video)

The above is the detailed content of Priority comparison: Which is higher, v-for or v-if?. 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 use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles