类名
:class
可以和普通类名共存
<div class="static" :class="{ 'active': isActive }"></div>
对象
普通方式
对象里面可以写多个属性
<div :class="{ 'active': isActive }"></div>
data: {
isActive: true
}
computed
<div :class="classes"></div>
data: {
isActive: true,
error: null
}
computed: {
classes: function () {
return {
active: this.isActice && !this.error,
'text-fail': this.error && this.error.type === 'fail'
}
}
}
数组
普通方式
<div :class="[{ 'active': isActive }, errorClass]"></div>
data: {
isActive: true,
errorClass: 'error'
}
computed
<button :class="classes"></button>
data: {
size: 'large',
disabled: true
}
computed: {
classes: function () {
return [
'btn',
{
['btn-' + this.size]: this.size !== '',
['btn-disabled']: this.disabled
}
];
}
}
三元表达式
<ul class="tabs">
<li @click="change(1)" :class="flag===1?'active':''">选项一</li>
<li @click="change(2)" :class="flag===2?'active':''">选项二</li>
</ul>
data: {
flag:1
},
methods:{
change: function (num) {
this.flag=num;
}
}
多个三元使用数组
<li :class="[flag===1?'active':'', flagOther===true?'active-other':'']"></li>