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?
<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>
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>