How to add a class conditionally in Vue?

in Vue class binding I think you can do this right inline in the element and actually add your class you'd like with an additional Vue computed class.

for example:

<div class="task_priority" :class="task.priority">{{ task.priority }}</div>

And do your styling as such (assuming the output for the task.priority is high,medium,low. it looks like it would be according to your posted code)

.task_priority.high {color: red}
.task_priority.medium {color: yellow}
.task_priority.low {color: green}

You can try this code above for conditional class in the html template

<element v-bind:class = "(condition)?'class_if_is_true':'else_class'"></element>

You may see the official vue documentation on this topic here.


If you only need to add a class if condition is true, you can use:

<p v-bind:class="{ 'className' : priority === low}"></p>

or you can use shorthand notation by omitting v-bind

<p :class="{ 'className' : priority === low}"></p>

This way you don't have to care if condition turned out to be false.