I have a project that I'm converting to Vue, and I was wondering how I can conditionally add a class to certain elements depending on what is returned from the database and rendered with Vue. Here is the code I had for the application when I was not using Vue:
$(document).ready(function() { $('.task_element').each(function(index, element) { if ($(element).find(".task_priority").text().trim() === "high") { $(element).addClass('high'); } else if ($(element).find(".task_priority").text().trim() === "medium") { $(element).addClass('medium'); } else if ($(element).find(".task_priority").text().trim() === "low") { $(element).addClass('low'); } });
});And this worked fine. But, I'm wondering is there a way to do this with Vue much more easily? Or would I have to find a way to throw this into my Vue app?
Here is part of the component:
<p> {{ task.description }} <span>priority</span>
</p>
<p> {{ task.priority }}
</p>What I want to do is bind the style of the badge (add one of the classes, either high, medium, or low) based on the value of the task_priority element. How would I achieve this?
4 Answers
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.
2If 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.
2in 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">{{ 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} 1 You can try creating function and pass condition compare value to it
<span bind:class="BindOrderStatus(order.status)">{{order.status}}</span>and write function like
methods: { BindOrderStatus: function (status){ if(status === "received") { return "badge badge-pill badge-primary pending-badge"; }else if(status === "accepted" || status === "auto-accepted"){ return "badge badge-pill badge-primary in-progress-badge" }.......etc conditions}
this may be help you for complex conditions.