Search code examples
javascriptvue.jsvuejs2conditional-formatting

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?


Solution

  • 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]
        }
      }
    }