Dynamically add and remove classes on mouseover - Vue.js

前端 未结 2 2176
走了就别回头了
走了就别回头了 2021-02-20 15:20

I can successfully add a class on mouseover with Vue. But I want to remove the class when the mouse leaves the element. What is the idiomatic way of handling this in Vue?

<
相关标签:
2条回答
  • 2021-02-20 15:34

    Listen for both mouseover and mouseout and set the class based on that.

    console.clear()
    
    new Vue({
      el: "#app",
      data:{
        isHovering: false
      }
    })
    .hovering{
      color: red
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
    <div id="app">
      <h1 @mouseover="isHovering = true" 
          @mouseout="isHovering = false" 
          :class="{hovering: isHovering}">
        {{ isHovering ? "Woot! Hovered" : "Hover over me" }}
      </h1>
    </div>

    Or just use CSS.

    console.clear()
    
    new Vue({
      el: "#app",
      data:{
        isHovering: false
      }
    })
    h1:hover{
      color: red
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
    <div id="app">
      <h1 @mouseover="isHovering = true" 
          @mouseout="isHovering = false" >
        {{ isHovering ? "Woot! Hovered" : "Hover over me" }}
      </h1>
    </div>

    0 讨论(0)
  • 2021-02-20 15:56

    A more scalable solution would be to use a directive:

    // Directives
    Vue.directive('add-class-hover', {
      bind(el, binding, vnode) {    
        const { value="" } = binding;
        el.addEventListener('mouseenter',()=> {
            el.classList.add(value)
        });
        el.addEventListener('mouseleave',()=> {
            el.classList.remove(value)
        });
      },
      unbind(el, binding, vnode) {
        el.removeEventListener('mouseenter');
        el.removeEventListener('mouseleave')
      }
    })
    
    new Vue({
      el: "#app"
    })
    .hoverClass {
    color: red;
    font-weight: 700;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <h1 v-add-class-hover="'hoverClass'">
        Text
      </h1>
    </div>

    0 讨论(0)
提交回复
热议问题