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.
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">
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
- {{ user.name }}
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) }
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)
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'}, ] ] }] }
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)}` + '})'
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() });
(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!

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.


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

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version
