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?
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.
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.
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.
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.
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] } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With