Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: Conditional class style binding

I have some data that is accessible via:

{{ content['term_goes_here'] }} 

... and this evaluated to either true or false. I'd like to add a class depending on the truthiness of the expression like so:

<i class="fa" v-bind:class="[{{content['cravings']}} ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i> 

where true gives me the class fa-checkbox-marked and false would give me fa-checkbox-blank-outline. The way I wrote it above gives me an error:

- invalid expression: v-bind:class="[{{content['cravings']}} ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']" 

How should I write it to be able to conditionally determine the class?

like image 389
Jeremy Thomas Avatar asked Apr 04 '17 14:04

Jeremy Thomas


People also ask

What is class binding in Vue?

Binding to Objects The above syntax means the presence of the active class will be determined by the truthiness of the data property isActive . You can have multiple classes toggled by having more fields in the object. In addition, the :class directive can also co-exist with the plain class attribute.

How do I add dynamic classes to Vue?

Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component.

How do I apply for CSS at Vue?

Adding CSS classes in Vue We should apply the button CSS classes to the <button> in our ToDoForm component. Since Vue templates are valid HTML, this is done in the same way to how you might do it in plain HTML — by adding a class="" attribute to the element.

What is the difference between V-model and V-bind?

v-bind is a one-way binding. v-model is used for binding form elements like inputs, radio buttons, textarea, checkboxes. It is used for binding data, attributes, expressions, class, styles. V-model is input value sensitive.


1 Answers

Use the object syntax.

v-bind:class="{'fa-checkbox-marked': content['cravings'],  'fa-checkbox-blank-outline': !content['cravings']}" 

When the object gets more complicated, extract it into a method.

v-bind:class="getClass()"  methods:{     getClass(){         return {             'fa-checkbox-marked': this.content['cravings'],               'fa-checkbox-blank-outline': !this.content['cravings']}     } } 

Finally, you could make this work for any content property like this.

v-bind:class="getClass('cravings')"  methods:{   getClass(property){     return {       'fa-checkbox-marked': this.content[property],       'fa-checkbox-blank-outline': !this.content[property]     }   } } 
like image 118
Bert Avatar answered Sep 24 '22 13:09

Bert