javascriptvue.jsjavascript-frameworkv-for

Use v-if for a specific element in a v-for


So I have the following HTML on my Vue page

    <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>

I want to show the element 'clickBox' when the user hovers over that row, if I use a v-if with a boolean and change it on mouseover they will all show since they are in a v-for, how I only show the div in the row they are hovering over?


Solution

  • In the v-for directive you can get the index of the element v-for="(profile, index)

    Use that index to only show the style you want it, in your template.

    for example.

    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#

    Edited

    It's perfeclty fine combine class="..." with the Vue binding :class="..."

    Edited 2

    For nested v-for declare another name for index.

    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>