Vue Js Change Text Color on Hover: To change the text color of an element in Vue.js on hover, you can use the v-bind
directive to bind a class to the element and use CSS to change the color. First, define a CSS class for the hover effect. Then, in your Vue template, use the v-bind
directive to bind the class to the element and use the @mouseover
and @mouseout
events to add and remove the class respectively.
How can I change the text color in Vue Js when the user hovers over it?
The code uses Vue’s ref
directive to bind an element to a variable in the component. The mouseover
and mouseout
event listeners are added to the element using the @
shorthand notation.
When the mouseover
event is triggered, the textColor
data property is set to red
, changing the color of the text to red. When the mouseout
event is triggered, the textColor
data property is set back to the original color, which is black.
The :style
binding is used to dynamically apply the color style to the element based on the value of the textColor
data property.
Overall, this code allows the text color of an element to change to red when the mouse is hovered over it and revert back to black when the mouse is moved away.
Vue Change Text Color on Hover Example
<div id="app">
<p ref="myParagraph" @mouseover="changeColor(true)" @mouseout="changeColor(false)">
Hover over me to change my color!
</p>
</div>
<script>
new Vue({
el: '#app',
methods: {
changeColor(isHovering) {
if (isHovering) {
this.$refs.myParagraph.style.color = 'red';
} else {
this.$refs.myParagraph.style.color = 'black';
}
}
}
});
</script>
Output of above example
Before hover on text
After Hover on Text