- 源码中找答案 https://github.com/vuejs/vue/blob/dev/src/compiler/codegen/index.js
在处理AST的时候,会先看静态节点,再看once,之后处理for,这里for会优先于if处理,所以代码生成的时候for会在if的前面
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
let code
if (el.component) {
code = genComponent(el.component, el, state)
} else {
let data
if (!el.plain || (el.pre && state.maybeComponent(el))) {
data = genData(el, state)
}
const children = el.inlineTemplate ? null : genChildren(el, state, true)
code = `_c('${el.tag}'${
data ? `,${data}` : '' // data
}${
children ? `,${children}` : '' // children
})`
}
// module transforms
for (let i = 0; i < state.transforms.length; i++) {
code = state.transforms[i](el, code)
}
return code
}
}
- 做个测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue事件处理</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="demo">
<h1>v-for和v-if谁的优先级高?应该如何正确使用避免性能问题?</h1>
<!-- <p v-for="child in children" v-if="isFolder">{{child.title}}</p> -->
<template v-if="isFolder">
<p v-for="child in children">{{child.title}}</p>
</template>
</div>
<script>
//创建实例
let vm = new Vue({
el:"#demo",
data(){
return {
children:[
{
title:"Aaron"
},
{
title:"Brown"
}
]
}
},
computed:{
isFolder(){
return this.children && this.children.length > 0;
}
}
});
console.log(vm.$options.render);
</script>
</body>
</html>
两者同级时渲染函数如下
(function anonymous() {
with(this){return _c('div',{attrs:{"id":"demo"}},[_c('h1',[_v("v-for和v-if谁的优先级高?应该如何正确使用避免性能问题?")]),_v(" "),
_l((children),function(child){return (isFolder)?_c('p',[_v(_s(child.title))]):_e()})],2)}
})
_l包含了isFolder的条件判断
两者不同级时渲染函数如下
(function anonymous() {
with(this){return _c('div',{attrs:{"id":"demo"}},[_c('h1',[_v("v-for和v-if谁的优先级高?应该如何正确使用避免性能问题?")]),_v(" "),
(isFolder)?_l((children),function(child){return _c('p',[_v(_s(child.title))])}):_e()],2)}
})
先判断了条件再看是否执行_l
结论:
1.显然v-for的优先级高于v-if
2.如果同时出现,每次渲染都会先执行循环在判断条件,无论如何循环都不可避免,浪费了性能(不推荐同时使用)
3.要避免这种情况,则在外层嵌套template,在这一层进行v-if判断,然后在内部进行v-for循环