我有一些数据可以通过以下方式访问:

{{ content['term_goes_here'] }}

... 这个数值估计为truefalse.我想根据表达式的真实性添加一个类,如下所示:

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

true给我fa-checkbox-marked级,false给我fa-checkbox-blank-outline级.我在上面写的方式给了我一个错误:

- 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?

推荐答案

使用object syntax.

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

当对象变得更复杂时,将其提取到方法中.

v-bind:class="getClass()"

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

最后,您可以将其应用于任何类似的内容属性.

v-bind:class="getClass('cravings')"

methods:{
  getClass(property){
    return {
      'fa-checkbox-marked': this.content[property],
      'fa-checkbox-blank-outline': !this.content[property]
    }
  }
}

Vue.js相关问答推荐

Vue ChildComponent (GrandchildComponent) 应该更新 ParentComponent 的列表

Vue composition api: 访问