Dynamically add and remove classes on mouseover - Vue.js

前端 未结 2 2152
走了就别回头了
走了就别回头了 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: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;
    }
    
    
    

    Text

提交回复
热议问题