In Vue.js, you can add styles to elements referenced by $refs
using either inline styles or by applying classes dynamically.
To do this we can:
1. Use Inline Styles
You can directly apply inline styles to the element using the style
property of the $refs
element.
<template>
<div ref="myElement">Element</div>
</template>
<script>
export default {
mounted() {
// Accessing the $refs element and applying inline styles
this.$refs.myElement.style.backgroundColor = "red";
this.$refs.myElement.style.color = "white";
},
};
</script>
2. Using Dynamic Classes
You can also dynamically add classes to the element referenced by $refs
and define styles for those classes in your CSS.
<template>
<div ref="myElement" :class="{ 'red-background': applyStyles }">Element</div>
</template>
<script>
export default {
data() {
return {
applyStyles: true, // Toggle this based on your requirement
};
},
};
</script>
<style>
.red-background {
background-color: red;
color: white;
}
</style>
In this example, the red-background
class is applied conditionally based on the value of applyStyles
.
You can toggle applyStyles
based on your requirements.
Choose the approach that best fits your use case. If you need to apply styles programmatically or conditionally, using inline styles might be more appropriate.
If you have predefined styles or want to apply styles based on certain conditions, using dynamic classes might be a better option.