vue.js

How to mouseover / hover for one item in a list in Vue?


I have this vue which render a list of fruits using v-for. When I mouseover, the css class hovering applies to all items instead of just one item. How do I fix it to the css class hovering to apply to just the item I mouseover?

new Vue({
  el: '#app',
  data: {
    fruits: ['apple','kiwi', 'orange'],
    isHovering: false
  }
})
.hovering{
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="fruit in fruits" @mouseover="isHovering = true" 
      @mouseout="isHovering = false" 
      :class="{hovering: isHovering}">
     {{ fruit }}
    </li>
  </ul>  
</div>


Solution

  • Erase the :class="{hovering: isHovering}" and use the common CSS pseudo class :hover instead, like this:

    <template>
    <div id="app">
        <ul>
          <li v-for="fruit in fruits" class="hover" :key="fruit" @mouseover="isHovering = true" 
            @mouseout="isHovering = false" >
          {{ fruit }}
          </li>
        </ul> 
      </div>
    </template>
    
    new Vue({
      el: '#app',
      data: {
        fruits: ['apple','kiwi', 'orange'],
        isHovering: false
      }
    })
    
    <style>
    .hover:hover{
      color: red
    }
    
    </style>