You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中v-for循环出现重复内容的解决方法咨询

Vue v-for渲染重复内容的解决办法

问题根源

你代码里存在两处完全相同的card结构:一处在v-for循环内部的v-if判断块里,另一处是循环外独立写的card,这是导致重复渲染的直接原因。另外循环内嵌套v-if不仅影响性能,也容易引发逻辑混乱。

具体解决方案

方案1:移除冗余的硬编码card

如果循环外的card是误写的,直接删除即可,只保留循环内的渲染逻辑:

<div v-for="n in follows" :key="n.follow_artist_Id">
    <div v-if="n.artist_id == sch.artist_id && n.sch_id == sch.sch_id">
        <div class="card card-schedule mb-3">
            ...
        </div>
    </div>
</div>

方案2:优化渲染逻辑(推荐)

先在JS中过滤出符合条件的数据,再进行渲染,避免循环内嵌套v-if:

  1. 在组件的计算属性中处理数据:
computed: {
    filteredFollows() {
        // 过滤出与当前sch匹配的follows项
        return this.follows.filter(item => {
            return item.artist_id === this.sch.artist_id && item.sch_id === this.sch.sch_id
        })
    }
}
  1. 模板中直接渲染过滤后的数组:
<div v-for="n in filteredFollows" :key="`${n.follow_artist_Id}-${n.sch_id}`">
    <div class="card card-schedule mb-3">
        ...
    </div>
</div>

额外注意事项

  • 确保v-for的key是唯一值:如果follow_artist_Id存在重复,可以用多个字段组合(比如上面的${n.follow_artist_Id}-${n.sch_id}),避免Vue虚拟DOM复用错误导致的异常渲染。

内容的提问来源于stack exchange,提问作者KHPK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 10:13:30