源码中找答案 src/compiler/codegen/index.js genElement()
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)
}
// 判断是否有 once 指令
else if (el.once && !el.onceProcessed) {
return genOnce(el, state)
}
// 判断是否有 v-for 指令
else if (el.for && !el.forProcessed) {
return genFor(el, state)
}
// 判断是否有 v-if 指令
} 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
}
}
测试代码:
<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 src="../../dist/vue.js"></script>
<script>
// 创建实例
const app = new Vue({
el: '#demo',
data() {
return {
children: [
{title:'foo'},
{title:'bar'},
]
}
},
computed: {
isFolder() {
return this.children && this.children.length > 0 }
},
});
console.log(app.$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)} })
两者不同级时,渲染函数如下:
(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)} })
结论:
1. v-for 优先级 比 v-if 高
2. 通过打印渲染函数可以发现,当 v-for与 v-if 同级时,列表渲染函数(_l)在 判断函数(isFolder) 外层。因此每次循环时,都会执行 判断函数。
3. 在源码中也可以看到, 会先判断有没有for指令,再判断有没有if指令。因此每次渲染都会先执行循环再判断条件,造成了性能浪费。
4. 解决方案:官网上也有提到 应当避免v-for与v-if一起使用,并且官网也给出了解决方案
两种情况:
(1)通过外部条件来判断是否需要渲染列表,可以在v-for的容器外面再套一层容器用来执行v-if,当v-if条件不满足时,避免了列表的渲染。大大的提升了性能。
(2)列表内选项属性的条件来判断是否需要渲染,可以通过一个computed计算属性,先将列表进行过滤再渲染,也提高了性能。