cft

Vue Tips: Dynamic CSS with Vue Reactive Variables

Ever want to put Javascript variables straight in your CSS? With Vue 3's composition API you can do just that.


user

Johnny Simpson

a year ago | 1 min read

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 elements class based on when certain conditions. For example, suppose if a variablecheckis set to true, we want adivto show asred, but otherwise it should beblue. 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'constcheck=true;letcolor=ref('#ff0000');if(check==true){color.value='#0000ff';}</script><template><inputvalue="Hello World"/></template>

Simple, right? Ifcheckistrue, thecolorvariable is '#0000ff'. Otherwise it's '#ff0000'. In our CSS, with Vue 3, we can now directly referencecolorby usingv-bind:

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

Now ifcolorupdates reactively, thecolorof input will change to whatever thecolorvariable 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.

Upvote


user
Created by

Johnny Simpson


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles