Vue.js is a JavaScript framework and is popular for its simplicity reactivity and performance. Like in any other frontend framework, you can easily apply logic on each component and work with that logic in your template.
In this article, I'll show you how to add a conditional class to an HTML-tag, so you can change CSS-classes based on a state of a variable.
Conditional rendering in Vue is very smart, so we can immediately start with an example.
Coding Example
In this example, we have a variable, which should be used for changing the div background-color. The div contains a paragraph, so you can see the change.
<div>
<p>
This background-color will be set by vue.js
</p>
</div>
In our Vue component we have a variable called state which is the boolean on which our background should change if it is true. You have to bind the class with the :class attribute, which is short for v-bind:class. In this attribute, you can insert an object of classes and variables. Is the variable true the class will be applied. In the following example, the class green sets the background-color the green.
<div :class="{ 'green' : state }">
<p>
This background-color will be set by vue.js
</p>
</div>
You can also add multiple conditions, for adding multiple conditions to a single tag by adding more items to the object.