Vue Dynamically Class

João Nascimento
2 min readAug 14, 2020

Dynamic class you can add a class by binding the v-bind property white your class:

<div v-bind:class=” ’yourClass’ ” ></div>

Dont forget to add extra quotes around our name class. For vue treat it as a string. you can also short the v-bind property, like:

<div :class=” ’yourClass’ ” ></div>

If you want to add other static class, you can do:

<div :class=” ’yourClass’ ” class=”yourStaticClass”></div>

For you dynamic class do not forget to add in data property, like so:

export default {
data() {
return {
yourClass: 'whatYouWant',
};
}
};
<style>
.whatYouWant {
color: blue;
background: white;
}
</style>

Conditional Classes

If you want to change dynamically a class to other, you may want to use this example, but there are many ways available:

example 1

<template>
<span
class="description"
:class="useTheme && theme"
>
This is how you add dynamic classes in Vue.
</span>
</template>

example 2

<template>
<span
class="basicStyle"
:class="blueMode ? 'blue-theme' : 'white-theme'"
>

</span>
</template>

example 3

<template>
<span :class="computedClass">

</span>
</template>
export default {
computed: {
computedClass() {
let className = 'default';

// logic of the class you want

return className;
}
}
}

Array Syntax

Combining the expressions you can do like:

<template>
<span
class="basicStyle"
:class="[
fontTheme,
blueMode ? 'blue-theme' : 'white-theme',
]"
>
</span>
</template>

So what happenning here??

With a array you set a two dinamically class on this component

If blueMode is true then vue will use blue-theme values if not it will use white-theme.

Custom Components

The logic is the same :

<template>
<CustomComponent
class="basicStyle"
:class="[
fontTheme,
blueMode ? 'blue-theme' : 'white-theme',
]"
>
</span>
</template>

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response