v-if 和 v-for 一起使用


在 vue 2.x 中, 在一个元素上同时使用 v-if 和 v-for 时, v-for 会优先作用。

在 vue 3.x 中, v-if总是优先于 v-for 生效

 

1、惯性使用,但 vue 2.x 中,不建议 v-for 和 v-if 使用

<div v-for="item in inHouseList" v-if="item.is_expired === 1">{{item.bar_code}}</div>

 

2、使用计算属性 computed ,选择性地渲染列表

    <div v-for="item in inHouseList" v-if="item.is_expired === 1">{{item.bar_code}}</div>
computed: {
    activeinHouseList: function() {
        return this.inHouseList.filter((item) => {
            return item.is_expired === 1 
        })
    }
}

 

3、避免渲染本该隐藏的列表项,将 v-if 放到循环列表元素的父元素中或使用template将 v-for 渲染的元素包起来,再在 template 上使用v-if

<template v-if="xxx=== 1">
    <div v-for="item in inHouseList"></div>
</template>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM