我有一些可以通过以下途径获得的数据:
{{ content['term_goes_here'] }}..。并将其评估为true或false。我想根据表达式的真实性添加一个类,如下所示:
<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']"我应该如何写它才能有条件地确定类?
发布于 2017-04-04 14:47:53
使用对象语法。
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]
    }
  }
}发布于 2017-04-04 14:48:23
<i class="fa" v-bind:class="cravings"></i>并加上计算:
computed: {
    cravings: function() {
        return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
    }
}发布于 2018-07-09 00:13:23
为什么不将一个对象传递给v-bind:class来动态切换类:
<div v-bind:class="{ disabled: order.cancelled_at }"></div>这是Vue文档推荐的内容。
https://stackoverflow.com/questions/43210508
复制相似问题