- 兩者同級
//html
<p v-for="item in list" :key="item.title" v-if="item.show">{{item.title}}</p>
//js
data(){
return{
list: [
{ title: 'nihao', show: false },
{ title: 'nihao2', show: true},
];
}}
渲染函數(shù)如下
//執(zhí)行 vm.$options.render
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
{ staticClass: "Contact" },
_vm._l(_vm.list, function(item) {
return item.show
? _c("p", { key: item.title }, [_vm._v(_vm._s(item.title))])
: _vm._e()
}),
0
)
}
_c
創(chuàng)建元素的虛擬節(jié)點
_v
創(chuàng)建文本的虛擬節(jié)點
_s
JSON.stringify
_l
是循環(huán)list的函數(shù)蔗彤,item.show
在每循環(huán)執(zhí)行的函數(shù)中判斷是否創(chuàng)建虛擬dom
- v-if在外層時
//html
<template v-if="show">
<p v-for="item in list" :key="item.title" >{{item.title}}</p>
</template>
//js
data(){
return{
show: true,
list: [
{ title: 'nihao', show: false },
{ title: 'nihao2', show: true},
];
}}
渲染函數(shù)如下
//執(zhí)行 vm.$options.render
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
{ staticClass: "Contact" },
[
_vm.show
? _vm._l(_vm.list, function(item) {
return _c("p", { key: item.title }, [_vm._v(_vm._s(item.title))])
})
: _vm._e()
],
2
)
}
他會先判斷vm.show
巢块,再去循環(huán)列表
所以v-for
比v-if
的優(yōu)先級更高溅潜,(源碼在處理AST的時候,會先處理for,在處理if)
如果
v-for
和v-if
同時出現(xiàn)時蒙幻,每次渲染都會先去循環(huán)再去判斷恶复,浪費了性能
如何規(guī)避州弟,在外層套個template
,在template
這層做v-if
判斷,
如果是根據(jù)數(shù)據(jù)中的字段去判斷是否顯示嘿悬,可以用計算屬性先過濾掉影藏的數(shù)據(jù)再去v-for
循環(huán)數(shù)據(jù)