首页 > 解决方案 > 如何避免 Vue.js v-for 复制引导行

问题描述

我有这个用于 wordpress 自定义主题的代码。我正在使用 REST API 和 Vue.js 获取数据,以使 DOM 在单击事件时动态更改。我面临一个小问题,我无法使用我想要的布局显示数据,这是因为当我v-if在要运行我的 vue 应用程序的主行上使用时,这将复制该行,但我只想拥有布局所需的列。我正在使用引导程序 4,并且列col-*-3在一行内,因此应该有四列。我该如何解决这个问题?

  <div class="row bg-light p-5 mt-3" v-for="cat in catList" >

    <div class="col-sm-12 col-md-12 col-lg-12 p-0">
      <div class="dropdown">
        <a class="text-uppercase dropdown-toggle dropdown-toggle-split" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          <?php _e('Collezioni'); ?>
        </a>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
          <a  v-on:click="displayCategory(cat.id)" class="dropdown-item" href="#">{{ cat.name }}</a>
        </div>
      </div>
    </div>

    <div class="col-sm-12 col-md-3 col-lg-3 col-background shadow-lg mt-5 mb-5 p-0" data-bg-url="" style="height:50vh;"></div>
    <div class="col-sm-12 col-md-3 col-lg-3 col-offset-top shadow-lg darkblue position-relative mt-5 mb-5 p-5">
      <small class="text-white m-0"></small>
      <h4 class="font-weight-bold text-white mt-2 mb-0" v-if="cat.name">{{ cat.name }}</h4>
      <h4 class="font-weight-bold text-white mt-2 mb-0" v-else>{{ cat.title }}</h4>
      <p v-if="cat.description">{{ cat.description }}</p>
      <p v-else>{{ cat.content }}</p>
    </div>

  </div>

更新

如果我使用 div<div v-for="cat in catList">来包装内容,布局将会中断。看画面

在此处输入图像描述

标签: twitter-bootstrapvue.js

解决方案


这里的问题是v-forif 重复行内的每个元素,包括行本身。我看到您需要在两个不同的地方显示类别数据,在下拉列表和最后的正方形上,但不需要循环并生成其间的所有其他元素。

您可以在这里做几件事,为底部 div(带有背景阴影的那些)创建另一个组件,或者通过移动 来创建两个单独的循环v-for="cat in catList",这将需要这三个更改

<!--remove the v-for="cat in catList" because this breaks everything-->
<div class="row bg-light p-5 mt-3">

<!--add one loop here for the dropdown elements-->
<a v-for="cat in catList" v-on:click="displayCategory(cat.id)" class="dropdown-item" href="#">{{ cat.name }}</a> 

<!--add the second loop here-->
<div v-for="cat in catList" class="col-sm-12 col-md-3 col-lg-3 col-offset-top shadow-lg darkblue position-relative mt-5 mb-5 p-5"> 

我在这里更新了小提琴https://jsfiddle.net/zgranda/y9d5fk67/2/

通过这样做,元素不应重复,但仍需要对阴影进行一些 CSS 修复

编辑:看到你的评论并编辑了小提琴,现在它应该循环两个 div,因为我不知道它应该是什么样子,所以你需要稍微调整一下 CSS https://jsfiddle.net/zgranda/2w39pdac/ 3/


推荐阅读