前端面试:Vue中v-if和v-for的优先级哪个更高

90 阅读1分钟

v-for和v-if的优先级

先说结论,vue2中,v-for的优先级更高。vue3中,v-if的优先级更高。


<template>
    <div>
        <div v-for="item in list" v-if="item">
            {{ item }}
        </div>
    </div>
</template>


<style lang="less" scoped></style>
<script>  
export default {  
  data() {  
    return {  
      list: [  0,1,2,3,4]  
    };  
  },  
// computed: {  
//     filteredList() {  
//       // 返回过滤后的列表 
//       return this.list.filter(item => item==true);  
//     }  
//   } 
};  
</script>

在这种情况下v-if的条件即使满足了也不会执行,0仍然会显示在页面上。他实际的执行过程是这样的。

this.list.map(function (item,index) {  
    if (index) {    
        return item 
        } 
})

将v-if和v-for一起写时,会导致性能问题,因为每次渲染时都会对整个列表进行遍历。因此官方是不推荐这种写法的。而官方给出的推荐的解决方案一种是,使用computed计算属性来过滤列表中的属性(就像我上面的代码中注释的那样),然后再v-for循环过滤后的列表。


另外一种是使用template包裹整个列表,将v-for写在template上,v-if写在内部。其实这两种方法都是避免了同时使用v-if和v-for。
<template>
    <template v-for="item in list">
        <div  v-if="item">
            {{ item }}
        </div>
    </template>
</template>


<style lang="less" scoped></style>
<script>  
export default {  
  data() {  
    return {  
      list: [0,1,2,3,4]  
    };  
  }}
</script>

总结

  1. vue2中,v-for的优先级更高。vue3中,v-if的优先级更高。
  2. 官方不推荐这种写法,会出现性能问题还会报错。
  3. 官方推荐使用计算属性来过滤你想要v-for循环的属性。
  4. 或者使用template包裹整个元素,来避免v-for和v-if同时出现。