美文网首页前端开发那些事儿
v-for和v-if不能直接一起使用

v-for和v-if不能直接一起使用

作者: 陶菇凉 | 来源:发表于2020-11-23 16:39 被阅读0次

不能直接这样写,会出现警告。

 <el-table-column v-for="(item,index) in checkList"  :key="index"  v-if="item.status" :prop="item.prop"  :label="item.name">    
            </el-table-column>  

正确写法

<template v-for="(item,index) in checkList">
            <el-table-column   :key="index"  v-if="item.status" :prop="item.prop"  :label="item.name">    
            </el-table-column>   
          </template>

注意:永远不要把 v-if 和 v-for 同时用在同一个元素上,带来性能方面的浪费(每次渲染都会先循环再进行条件判断)
如果避免出现这种情况,则在外层嵌套template(页面渲染不生成dom节点),在这一层进行v-if判断,然后在内部进行v-for循环

<template v-if="isShow">
    <p v-for="item in items">
</template>

如果条件出现在循环内部,可通过计算属性computed提前过滤掉那些不需要显示的项

computed: {
    items: function() {
      return this.list.filter(function (item) {
        return item.isShow
      })
    }
}

相关文章

网友评论

    本文标题:v-for和v-if不能直接一起使用

    本文链接:https://www.haomeiwen.com/subject/radviktx.html