1
1
## v-if和v-for哪个优先级更高?
2
2
3
- 分析:此题考查常识,文档中曾有 [ 详细说明 ] ( https://cn.vuejs.org/v2/style-guide/#%E9%81%BF%E5%85%8D-v-if-%E5%92%8C-v-for-%E7%94%A8%E5%9C%A8%E4%B8%80%E8%B5%B7%E5%BF%85%E8%A6%81 ) ;也是一个很好的实践题目,项目中经常会遇到,能够看出面试者应用能力。
3
+ 分析:此题考查常识,文档中曾有详细说明 [ v2 ] ( https://cn.vuejs.org/v2/style-guide/#%E9%81%BF%E5%85%8D-v-if-%E5%92%8C-v-for-%E7%94%A8%E5%9C%A8%E4%B8%80%E8%B5%B7%E5%BF%85%E8%A6%81 ) | [ v3 ] ( https://vuejs.org/style-guide/rules-essential.html#avoid-v-if-with-v-for ) ;也是一个很好的实践题目,项目中经常会遇到,能够看出面试者应用能力。
4
4
5
5
6
6
18
18
19
19
回答范例:
20
20
21
- 1 . v-for优先于v-if被解析
21
+ 1 . 在 ` Vue 2 ` 中, ` v-for ` 优先于 ` v-if ` 被解析;但在 ` Vue 3 ` 中,则完全相反, ` v-if ` 的优先级高于 ` v-for ` 。
22
22
23
23
2 . 我曾经做过实验,把它们放在一起,输出的渲染函数中可以看出会先执行循环再判断条件
24
24
40
40
41
41
知其所以然:
42
42
43
- 做个测试, [ 01 .html] ( ./01 .html )
43
+ 在 ` Vue 2 ` 中做个测试, [ test .html] ( ./test .html )
44
44
两者同级时,渲染函数如下:
45
45
46
46
@@ -51,7 +51,30 @@ with(this){return _c('div',{attrs:{"id":"app"}},_l((items),function(item){return
51
51
}
52
52
```
53
53
54
+ 在 ` Vue 3 ` 中做个测试,[ test-v3.html] ( ./test-v3.html )
55
+ 两者同级时,渲染函数如下:
56
+
57
+ ``` js
58
+ (function anonymous (
59
+ ) {
60
+ const _Vue = Vue
61
+
62
+ return function render (_ctx , _cache ) {
63
+ with (_ctx) {
64
+ const { renderList: _renderList , Fragment: _Fragment , openBlock: _openBlock , createElementBlock: _createElementBlock , toDisplayString: _toDisplayString , createCommentVNode: _createCommentVNode } = _Vue
65
+
66
+ return shouldShowUsers
67
+ ? (_openBlock (true ), _createElementBlock (_Fragment, { key: 0 }, _renderList (items, (item ) => {
68
+ return (_openBlock (), _createElementBlock (" div" , { key: item .id }, _toDisplayString (item .name ), 1 /* TEXT */ ))
69
+ }), 128 /* KEYED_FRAGMENT */ ))
70
+ : _createCommentVNode (" v-if" , true )
71
+ }
72
+ }
73
+ })
74
+ ```
54
75
55
76
56
- 源码中找答案compiler/codegen/index.js
77
+ 源码中找答案:
78
+ ` Vue 2 ` :[ compiler/codegen/index.js] ( https://github1s.com/vuejs/vue/blob/dev/src/compiler/codegen/index.js#L65-L69 )
79
+ ` Vue 3 ` :[ compiler-core/src/codegen.ts] ( https://github1s.com/vuejs/core/blob/main/packages/compiler-core/src/codegen.ts#L586-L587 )
57
80
0 commit comments