對(duì)應(yīng)源碼的位置compiler/codegen/index.js
1.測試的案例代碼
<body>
<div id="demo">
<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>
//創(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>
兩者同級(jí)時(shí),渲染函數(shù)如下:
? anonymous(
) {
with(this){return _c('div',{attrs:{"id":"demo"}},_l((children),function(child){return (isFolder)?_c('p',[_v(_s(child.title))]):_e()}),0)}
}
_l包含了isFolder的條件判斷(_l列表渲染函數(shù))
兩者不同級(jí)時(shí),渲染函數(shù)如下:
? anonymous(
) {
with(this){return _c('div',{attrs:{"id":"demo"}},[(isFolder)?_l((children),function(child){return _c('p',[_v(_s(child.title))])}):_e()],2)}
}
先判斷了條件再看是否執(zhí)行_l
2.結(jié)論:
1.顯然v-for優(yōu)先于v-if被解析
我寫了一個(gè)測試的代碼并且在源碼中找到了這個(gè)結(jié)論
codegen>index.js中for的優(yōu)先級(jí)高于if
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) {//for
return genFor(el, state)
} else if (el.if && !el.ifProcessed) {//if
...
2.如果同時(shí)出現(xiàn)铅碍,每次渲染都會(huì)先執(zhí)行循環(huán)再判斷條件,無論如何循環(huán)都不可避免,浪費(fèi)了性能
3.要避免出現(xiàn)這種情況线椰,則在外層嵌套template,在這一層進(jìn)行v-if判斷胞谈, 然后在內(nèi)部進(jìn)行v-for循環(huán)
4.有一個(gè)問題,當(dāng)循環(huán)項(xiàng)中有需要判斷的屬性怎么辦呢憨愉?這個(gè)時(shí)候應(yīng)該用計(jì)算屬性做一下過濾烦绳,避免循環(huán)中還要進(jìn)行判斷