Dynamically add and remove classes on mouseover - Vue.js
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>
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>
In case someone is looking for something that actually works with v-for
, use this:
<div v-for="(item, index) in [1,2,3,4,5,6,7,8]" @mouseenter="state.hover=index" @mouseleave="state.hover=false">
<p :class="{ 'yourClass': state.hover == index }">Hello World</p>
</div>
The above answers will trigger all of your elements inside a v-for
loop at the same time.
Add the following to the div you want to animate on hover :
@mouseover="isHovering = item.id" @mouseout="isHovering = false" :class="isHovering == item.id ? 'slower animated pulse' : ''"