【问题标题】:Use v-if for a specific element in a v-for对 v-for 中的特定元素使用 v-if
【发布时间】:2019-05-30 05:32:05
【问题描述】:

所以我的 Vue 页面上有以下 HTML

    <div v-for="profile in lab.profiles" v-if="edit || profile.active" class="lab-tests-row-div" @mouseover="">
        <div class="clickBox" :class="['clickBox-' + lab.id + '-' + profile.id]" @click="openInfoPopup"></div>
        <p class="lab-tests-row test-info-row" v-bind:class="{'active': profile.active}">
            <span v-bind:class="{'opacity50':!profile.active}">{{profile.name}}</span> 
            <i v-if="edit" class="fa fa-minus pull-right removeTestIcon" aria-hidden="true" @click="toggleProfile(lab.id, profile.id)"></i>
            <span class="pull-right" v-bind:class="{'opacity50':!profile.active}">{{profile.code}}</span>
        </p>
    </div>

我想在用户将鼠标悬停在该行上时显示元素“clickBox”,如果我使用带有布尔值的 v-if 并在鼠标悬停时更改它,它们都会显示,因为它们在 v-for 中,我如何只在他们悬停的行中显示 div?

【问题讨论】:

    标签: javascript vue.js javascript-framework v-for


    【解决方案1】:

    v-for 指令中,您可以获得元素v-for="(profile, index) 的索引

    使用该索引仅在模板中显示您想要的样式。

    例如。

    new Vue({
      el: '#app',
      data: {
        selected : 0
      }
    })
    .selectedClass {
      background: lightblue
    }
    
    .hoverClass:hover {
      background: lightcoral
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <main id="app">
      <div v-for="(elem, index) in 4">
        <p class="hoverClass" :class="{'selectedClass': selected === index}" @click="selected = index" >{{elem}}</p>
      </div>
    </main>
    https://stackoverflow.com/posts/54025706/edit#

    已编辑

    class="..." 与 Vue 绑定 :class="..." 完美结合

    已编辑 2

    对于嵌套的v-for,为索引声明另一个名称。

    new Vue({
      el: '#app'
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <main id="app">
        <div v-for="(item, i) in 2">
           <div v-for="(elem, j) in 3">
            v-for item {{ i }} v-for elem {{ j }}
           </div>
        </div>
    </main>

    【讨论】:

    • 此解决方案的问题是 v-for 嵌套在另一个 v-for 中,因此其他 v-for 中具有相同索引的所有其他元素也会显示。
    • 这里的例子:codesandbox.io/s/vjn655zyx7 selected 为 0,但第一项显示在两个子列表中,而不是我想要的一个
    猜你喜欢
    • 2022-07-15
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2020-06-28
    • 2022-01-01
    • 2018-03-07
    • 2021-08-12
    相关资源
    最近更新 更多