Vue Tip: Binding Reactive Values to CSS Properties
Reactivity is a core API in Vuejs, we can embed reactive component in Vuejs template and script tags but did you know we can also bind reactive element to CSS properties in Vuejs ? Well we can. Vuejs allows us to bind reactive elements to CSS styling properties.
This can be useful in scenarios where we want to apply various styling when certain component values change.
from Programmer Humor
Binding Reactive values in CSS
<script setup>
import { ref } from 'vue'
const msg = ref('Hello World!')
const helloColor = ref('red')
function changeColor(){
const randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
helloColor.value = randomColor;
}
</script>
<template>
<h1 class="hello">{{ msg }}</h1>
<button type="button" @click="changeColor">Change Hello World Color</button>
</template>
<style scoped>
.hello{
color: v-bind(helloColor);
}
</style>
From the code snippet above, we have a helloColor
which is a reactive variable which we use to bind to the color CSS property. We have a button with a function that will change the helloColor
every time it is clicked.
To bind the reactive helloColor
variable, we need to use the v-bind
and attach the reactive variable to it.
That is how we can bind reactive values to CSS properties in Vuejs. You can play around with the code on Vuejs Playground.
Resources
Before You Go
Thank you for following this guide. Sharing it with others would be greatly appreciated. Should you have any questions, suggestions, or just want to chat, feel free to connect with me on X via @amjohnphilip. Your engagement is valued!
More Reads
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: Stackademic | CoFeed | Venture
- More content at PlainEnglish.io