Vue.js:条件类样式 [英] Vue.js: Conditional class styling
本文介绍了Vue.js:条件类样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些可以通过以下方式访问的数据:
I have some data that is accessible via:
{{ content['term_goes_here'] }}
...并评估为 true
或假
。我想根据表达式的真实性添加一个类,如下所示:
... 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>
其中 true
给我的课程 fa-checkbox-marked
而false会给我 fa-checkbox-blank-outline
。我在上面写的方式给出了一个错误:
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']"
如何编写它以便有条件地确定班级?
推荐答案
使用对象语法。
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]
}
}
}
这篇关于Vue.js:条件类样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文