Js: 条件类样式绑定

我有一些数据可以通过以下途径获得:

{{ 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']"

我应该如何编写它,以便能够有条件地确定类?

252441 次浏览

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]
}
}
}
<i class="fa" v-bind:class="cravings"></i>

and add in computed :

computed: {
cravings: function() {
return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
}
}

the problem is blade, try this

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

Why not pass an object to v-bind:class to dynamically toggle the class:

<div v-bind:class="{ disabled: order.cancelled_at }"></div>

This is what is recommended by the Vue docs.

if you want to apply separate css classes for same element with conditions in Vue.js you can use the below given method.it worked in my scenario.

html

 <div class="Main" v-bind:class="{ Sub: page}"  >

in here, Main and Sub are two different class names for same div element. v-bind:class directive is used to bind the sub class in here. page is the property we use to update the classes when it's value changed.

js

data:{
page : true;
}

here we can apply a condition if we needed. so, if the page property becomes true element will go with Main and Sub claases css styles. but if false only Main class css styles will be applied.

You could use string template like with backticks `` :

:class="`${content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline'}`"