Mastering Dynamic Styling in Vue.js: Use This Advanced Technique for Reactivity in Your Styles
I’m constantly perplexed that there’s boundless things I’m still learning about the VueJS framework, even after almost 2 years of working with it.
Today that thing in question is, you can declare reactive data inside the
Granted, this knowledge may be slightly outdated, as this was a readily available feature since 2021, but nonetheless, it’s never too late to learn!
Let’s dive in, shall we?
Say you want to dynamically bind some styling to your HTML element based on reactive data in your <script
tag.
This is one way of doing so, and may be the go-to way for some of you:
<template>
<div :class="{ example: isRed }">Style reactivity!</div>
</template>
<script>
export default {
data() {
return {
isRed: true,
};
},
};
</script>
<style>
.example {
color: red;
}
</style>
In the above, the styling for the .example
class is conditionally applied based on the truthiness of the isRed
variable. On the browser, this is will be the result.
Neat! But what happens if we don’t want to keep track of a true/false value, but instead access a reactive data directly from the script
tag?
Easy.
<template>
<div class="example">Style reactivity!</div>
</template>
<script>
export default {
data() {
return {
redColor: "red",
};
},
};
</script>
<style>
.example {
color: v-bind(redColor);
}
</style>
With the above, you’ll achieve the exact same result.
It doesn’t just stop there, you can even bind styling with JS objects, like the example below.
<template>
<div>
<div class="text">Applying dynamic styles</div>
</div>
</template>
<script>
export default {
data() {
return {
color: 'red',
font: {
style: 'italic',
weight: '900',
},
}
},
}
</script>
<style>
.text {
color: v-bind(color);
/* wrapped in quotes */
font-style: v-bind('font.style');
font-weight: v-bind('font.weight')
}
</style>
Of course, there’s more writing involved, but it’s a great trick in case you want to constrict all your styling into 1 object instead of declaring multiple variables.
With this, there are a multitude of cools things you can achieve, such as changing the color of text with a button click.
<div>
<div class="text">Reactive!</div>
<button @click="color = 'orange'">Make Orange</button>
</div>
Here’s some material for further learning:
How to Use Vue CSS Variables — Reactive Styles RFC — LearnVue | LearnVue
(3) We can use REACTIVE VARIABLES in Vue CSS!! — YouTube
Stackademic
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us on Twitter(X), LinkedIn, and YouTube.
- Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.