源碼中找答案compiler/codegen/index.js
<p v-for="item in items" v-if="condition">
測(cè)試代碼:
<!DOCTYPE html>
<html>
<head> <title>Vue事件處理</title>
</head>
<body>
<div id="demo">
<h1>v-for和v-if誰(shuí)的優(yōu)先級(jí)高?應(yīng)該如何正確使用避免性能問(wèn)題?</h1>
<template v-if="isFolder">
<p v-for="child in children">{{child.title}}</p>
</template>
</div>
<script src="../../dist/vue.js"></script>
<script>
// 創(chuàng)建實(shí)例
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>
兩者同級(jí)時(shí)做祝,渲染函數(shù)如下:
(function anonymous(
){
with(this){return _c('div',{attrs:{"id":"demo"}},[_c('h1',[_v("v-for和v-if誰(shuí)的優(yōu)先 級(jí)高?應(yīng)該如何正確使用避免性能問(wèn)題?")]),_v(" "),
_l((children),function(child){return (isFolder)?_c('p', [_v(_s(child.title))]):_e()})],2)}
})
_l包含了isFolder的條件判斷
兩者不同級(jí)時(shí),渲染函數(shù)如下
(function anonymous(
){
with(this){return _c('div',{attrs:{"id":"demo"}},[_c('h1',[_v("v-for和v-if誰(shuí)的優(yōu)先 級(jí)高?應(yīng)該如何正確使用避免性能問(wèn)題?")]),_v(" "), (isFolder)?_l((children),function(child){return _c('p', [_v(_s(child.title))])}):_e()],2)}
})
先判斷了條件再看是否執(zhí)行_l
結(jié)論:
- 顯然v-for優(yōu)先于v-if被解析
- 如果同時(shí)出現(xiàn)蠕啄,每次渲染都會(huì)先執(zhí)行循環(huán)再判斷條件场勤,無(wú)論如何循環(huán)都不可避免,浪費(fèi)了性能
- 要避免出現(xiàn)這種情況歼跟,則在外層嵌套template却嗡,在這一層進(jìn)行v-if判斷,然后在內(nèi)部進(jìn)行v-for循環(huán)
- 如果條件出現(xiàn)在循環(huán)內(nèi)部嘹承,可通過(guò)計(jì)算屬性提前過(guò)濾掉那些不需要顯示的項(xiàng)