Home > Net >  Trigger single component of hover effect in multi component of `v-for`
Trigger single component of hover effect in multi component of `v-for`

Time:02-10

all. I currently meet a CSS problem with Vue. Suppose I want to render multiple component by using v-for, and I want bind hover effect with each component. Once I hover my mouse on one component, there will be hover effect on that component, and the other components will keep unchanged. However, as I typed code below, if I hover my mouse on one component, all component will be affected. So, my question is how could I achieve my purpose?

<component v-for="(item, index) in items" :key="index">
  <div @mouseover="hover = true" @mouseleave="hover = false">
     <div v-if="hover" > Hover Effect </div>
     <div v-else> Normal Effect </div>
  </div>
</component> 

CodePudding user response:

The answer is pretty straightforward for this problem. What you have to do is keep track of the index or the key of the element which you hover and clear it when you leave. You can write two specific methods for this if you want.

<component v-for="(item, index) in items" :key="index">
 <div @mouseover="hoveredIndex = index" @mouseleave="hoveredIndex = -1">
  <div v-if="hoveredIndex===index" > Hover Effect </div>
    <div v-else> Normal Effect </div>
   </div>
</component> 
  • Related