paint-brush
How to Create Dynamic CSS Using Vue Reactive Variablesby@smpnjn
1,214 reads
1,214 reads

How to Create Dynamic CSS Using Vue Reactive Variables

by Johnny SimpsonSeptember 4th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Vue 3 allows you to use Vue reactive variables straight in your CSS. You can use the composition API to update an element’s class based on when certain conditions occur. For example, suppose a variable `check` is set to true, we want a `div` to show as **red**, but otherwise, it should be **blue**. In our CSS, we can now directly reference `color` by using `v-bind`: /* color: v-bind(color)color; /* color' is '#0000ff' or '#ff0000'
featured image - How to Create Dynamic CSS Using Vue Reactive Variables
Johnny Simpson HackerNoon profile picture


If you use Vue, you might be used to having to apply different classes to tags based on the logic in your code. That's because we might want to reactively update an element’s class based on when certain conditions. For example, suppose a variable check is set to true, we want a div to show as red, but otherwise, it should be blue. For such use cases, it's common to see the following code:


<div :class="check === true ? 'red' : 'blue'">
    Hello World
</div>


Did you know, however, that you can actually put Vue reactive variables straight in your CSS with Vue 3? We have to use the composition API (read more: difference between composition and options API), but once we do, we can avoid the code below and put our variable straight in our CSS.


Let's look at a simple example. Suppose we have the following script in our Vue template:

<script setup>
import { ref } from 'vue'

const check = true;
let color = ref('#ff0000');
  
if(check == true) {
  color.value = '#0000ff';
}
</script>
<template>
  <input value="Hello World" />
</template>


Simple, right? If check is true, the color variable is '#0000ff'. Otherwise, it's '#ff0000'. In our CSS, with Vue 3, we can now directly reference color by using v-bind:

<style>
  input {
    color: v-bind(color)
  }
</style>


Now if color updates reactively, the color of input will change to whatever the color variable is set to. That means you can avoid some awkward logic in your HTML tags, and start using Javascript variables straight in your CSS - and I think that's pretty cool.


Also Published here