1. v-if和v-for的哪个的优先级更高?同时出现的时候如何优化得到更好的性能?
这部分的源码解析可以在vue的src\compiler\codegen\index.js里找到。如图所示:
v-for是优于v-if的。我们也可以通过例子分别来看下v-if和v-for不同写法的执行结果
<!DOCTYPE html>
<html>
<head>
<title>Vue事件处理</title>
</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 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)}})
结论:
- 显然v-for优先于v-if被解析(把你是怎么知道的告诉面试官)
- 如果同时出现,每次渲染都会先执行循环再判断条件,无论如何循环都不可避免,浪费了性能
- 要避免出现这种情况,则在外层嵌套template,在这一层进行v-if判断,然后在内部进行v-for循环
- 如果条件出现在循环内部,可通过计算属性提前过滤掉那些不需要显示的项