Home » vue » How can I make a selective hover in Vue Js?

How can I make a selective hover in Vue Js?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I want a hover button to only style the nested elements inside it.
Currently in my code hovering over a single button will style the nested elements inside all its sibling buttons.

Any suggestions?

<div id="app">
  <button
   v-on:mouseover="isHovering = true"
   v-on:mouseout="isHovering = false">Button 1
  </button>
    <p v-bind:class="{hovering: isHovering}">
    {{ isHovering ? "Yes" : "No" }}
    </p>
  <button
    v-on:mouseover="isHovering = true"
    v-on:mouseout="isHovering = false">Button 2
  </button>
    <p v-bind:class="{hovering: isHovering}">
    {{ isHovering ? "Yes" : "No" }}
    </p>
</div>
const app = new Vue({
  el: "#app",
  data: {
    isHovering: false
  }
})


.hovering {
  display: red;
}
Answers:

If you are only concerned with styling, you can succeed with pure css using the :hover selector.

Example for your use case:

button:hover + p {
  background-color: red;
}

I want a hover button to only style the nested elements inside it.

This is not true, your p tags are not inside your button tags (even though you indented your code as such).

###

In your current code you only have 1 data property “isHovering”, and both of your <p> elements use it to conditionally use the .hovering {display: red}.

You could create another data property for your second button. If you are going to have a lot of buttons trying to do this, your code will get out of hand quite quickly.

<button
  v-on:mouseover="isSecondButtonHovering = true"
  v-on:mouseout="isSecondButtonHovering = false">Button 2
</button>
<p :class="{hovering: isSecondButtonHovering}">
  {{ isSecondButtonHovering ? "Yes" : "No" }}
</p>