v-if和v-for哪个优先级更高?

首先在实际开发阶段,不应该把v-if和v-for在同一个标签中使用,

在vue2中,v-for的优先级是高于v-if的,如果同时出现,每次渲染都会先执行循环再判断条件,无论如何循环都不可避免,浪费了性能;另外需要注意的是在vue3则完全相反,v-if的优先级高于v-for,所以v-if执行时,它调用的变量还不存在,就会导致异常。

通常有两种情况下导致我们这样做

  • 为了过滤列表中的项目(比如:v-for="user in users" v-if="user.isActive")。此时定义一个计算属性(比如:activeUsers),让其返回过滤后的列表即可(比如:users.filter(u=>u.isActive)
  • 为了避免渲染本应该被隐藏的列表(比如v-for="user in users" v-if="shouldShowUsers"),此时把v-if移至容器元素上(比如ulol)或者外面包一层template即可。
 <div id="app">
        <p v-for="child in children" v-if="isFolder">{{child.title}}</p>
    </div>
    <script>
        const vm=new Vue({
            el:'#app',
            data(){
                return{
                   children:[
                     {
                        title:'red'
                     },
                     {
                        title:'green'
                     }
                   ]
                }
            },
            computed:{
                isFolder(){
                    return this.children&&this.children.length>0
                }
            }
        })
  console.log(vm.$options.render);

渲染函数如下:

ƒ anonymous(
) {
with(this){return _c('div',{attrs:{"id":"app"}},_l((children),function(child){return (isFolder)?_c('p',[_v(_s(child.title))]):_e()}))}
}

优化后代码:

<template v-if="isFolder">
     <p v-for="child in children">{{child.title}}</p>
</template>

渲染函数如下:

ƒ anonymous(
) {
with(this){return _c('div',{attrs:{"id":"app"}},[(isFolder)?_l((children),function(child){return _c('p',[_v(_s(child.title))])}):_e()],2)}
}

 

posted @ 2022-06-22 19:14  bug制造者~~  阅读(507)  评论(0)    收藏  举报