Search code examples
javascriptvue.jshovermouseoverv-for

In vue, how to not allow mouseover to affect every element of the list?


I have a v-for, every element of the list has a mouseover event. I would like that when mouseover on that element, a variable value is changed and so a div appears next to that element(.checkbox div). But instead, since all elements use the same variable all divs appear. Here's my code:

<md-card v-for="route in routes" :key="route.id">
    <md-card-area>
      <div class="checkbox" v-show="hover == true" @mouseover="hover = true">
        <input type="checkbox" v-model="route.checked"/>
      </div>
      <div @mouseover="hover = true" @mouseout="function() { if (route.checked == false) hover = false }">
       </div>
    </md card-area>
</md-card>

I have tried to use mouseover.native but it won't work. I have also tried using instead of changing hover variable, changing route.hover variable but it won't be changed.


Solution

  • Add another variable called currentIndex :

    data(){
      return{
        currentIndex:-1,
         hover:false,
    
      }
    }
    

    add index in v-for loop and update the currentIndex with the hovered index and add this condition hover == true && currentIndex===index:

    <md-card v-for="(route,index) in routes" :key="route.id">
        <md-card-area>
          <div class="checkbox" v-show="hover == true && currentIndex===index" @mouseover="hover = true" >
            <input type="checkbox" v-model="route.checked"/>
          </div>
          <div @mouseover="hover = true;currentIndex=index" @mouseout="function() { if (route.checked == false){ hover = false; currentIndex=-1;} }">
           </div>
        </md card-area>
    </md-card>