Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  130] [ 2]  / answers: 1 / hits: 33169  / 6 Years ago, tue, february 20, 2018, 12:00:00

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?



<template>
<div id=navigation>
<div class=nav-container>
<nav>
<router-link to=/ class=home>Ping Party</router-link>
<div class=navigation-actions>
<router-link to=/sign_in v-if=!isLoggedIn class=sign_in>Sign In</router-link>
<router-link to=/sign_up v-if=!isLoggedIn @mouseover.native=mouseOver class=sign_up ref=sign_up>Sign Up</router-link>
<router-link to=/users v-if=isLoggedIn class=users>Users</router-link>
<v-btn :click.prevent=signOut() v-if=isLoggedIn>Sign Out</v-btn>
</div>
</nav>
</div>
</div>
</template>

<script>
import SignUp from ../forms/SignUp;
import SignIn from ../forms/SignIn;

export default {
components: {
SignUp,
SignIn
},
computed: {
isLoggedIn () {
return this.$store.getters.isLoggedIn
}
},
methods: {
signOut: function() {
this.$store.commit(LOGOUT)
this.$store.commit(FLASH_MESSAGE, {
message: Signed Out Successfully,
show: true,
styleClass: error,
timeOut: 4000
})
this.$router.push('/')
},
mouseOver: function() {
this.$refs.sign_up.$vnode.elm.classList.add(hovered)
}
}
}
</script>


As you can see on mouseover I call the mouseOver function and this successfully adds the class to the element. But now when the users leaves the element the class remains. How can I have the class remove when the user leaves the element? Thanks for the help.


More From » vue.js

 Answers
2

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>




[#55101] Friday, February 16, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamronr

Total Points: 749
Total Questions: 110
Total Answers: 122

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
kamronr questions
Mon, Dec 21, 20, 00:00, 4 Years ago
Fri, Oct 16, 20, 00:00, 4 Years ago
Sat, Oct 3, 20, 00:00, 4 Years ago
Sun, Jul 28, 19, 00:00, 5 Years ago
;