DEV Community

Cover image for Implement Hover in Vue
Mohcin Bounouara
Mohcin Bounouara

Posted on

Implement Hover in Vue

We used to implement showing something on hover using JQuery or pure CSS but if you are starting using Vue Js and you wanna do the same you will face the problem, there no functionality built in or pre-defined so we will try to make this simple implementation for that.

Let us first make a reminder of this functionality in JQuery and css.

Here is a Jquery example using mouseenter() and mouseleave():

Here is a Jquery example using pure css:

After this simple reminder about this common functionalities I will do the same using Vue Js.
Ok!, to do that in vue we will use Vue events to listen to DOM events when the mouse enters and leaves, and update our state based on that.
We will use v-on directive to listen to the mouse moves. we can just write @event to define v-on:event.

<div id="app">

  <p>
    Hover on me to show text
  </p>
   <p>
   This the text who shown after hover
  </p>

</div>
Enter fullscreen mode Exit fullscreen mode
new Vue({
  el: '#app',
  data: {
    toShowOnHover: false,
  }
)}
Enter fullscreen mode Exit fullscreen mode

Now any element with property "toShowOnHover" will be shown on hover after we setup the methods

We will use v-show to show the element who have the vue property on hover.
So our code will transform to something bellow:

<div id="app">

  <p @mouseover="mouseEnter" @mouseleave="mouseLeave">
    Hover on me to show text
  </p>
   <p v-show="toShowOnHover">
   This the text who shown after hover
  </p>

</div>
Enter fullscreen mode Exit fullscreen mode
new Vue({
  el: '#app',
  data: {
    toShowOnHover: false,
  },
  methods: {
        mouseEnter: function(){
            this.toShowOnHover = !this.toShowOnHover;   
        },
        mouseLeave: function(){
            this.toShowOnHover = false;   
        }
  }
})
Enter fullscreen mode Exit fullscreen mode
  • The mouseEnter() function let us show the element p who had already the property "toShowOnHover"
  • The mouseLeave() function let us hide the element p to return to the base state

DEMO IN ACTION

Conclusion

Now you have the start up keys to achieve any thing you wanna show when users hover an element in your next vue app.

Go ahead and happy coding

Discussion (2)

Collapse
maprangsoft profile image
Maprangsoft

thank you very much.

Collapse
bn_geek profile image
Mohcin Bounouara Author

You are welcome