Categories
Vue Answers

How to Do Something When we Mouse Over or Hover Over an Element with Vue.js?

Spread the love

Sometimes, we want to do something when we mouse over or hover over an element with Vue.js.

In this article, we’ll look at how to do something when we mouse over or hover over an element with Vue.js.

Do Something When we Mouse Over or Hover Over an Element with Vue.js

To do something when we mouse over or hover over an element with Vue.js, we can listen to the mouseover and mouseleave events.

For instance, we can write:

<template>
  <div id="app">
    <div @mouseover="hovered = true" @mouseleave="hovered = false">
      <p>hello world</p>
      <p v-show="hovered">hovered</p>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return { hovered: false };
  },
};
</script>

We have the hovered reactive property which is set to false initially.

Then we add the @mouseover directive and set its value to hovered = true , and we set the @mouseover directive to hovered = false to toggle the hovered reactive property when we move our more into the div and out of it respectively.

And we have the v-show directive to show the second p element when hovered is true .

Now when our mouse is in the div, we see ‘hovered’ displayed.

And we move our mouse out of the div, ‘hovered’ disappears.

Conclusion

To do something when we mouse over or hover over an element with Vue.js, we can listen to the mouseover and mouseleave events.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *