Vue.js: Conditional class style binding

后端 未结 5 795
难免孤独
难免孤独 2020-11-28 08:51

I have some data that is accessible via:

{{ content[\'term_goes_here\'] }}

... and this evaluated to either true or fals

5条回答
  •  [愿得一人]
    2020-11-28 09:39

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

提交回复
热议问题