在Vue中,绑定class和style可以通过对象语法或数组语法来实现。
对象语法适用于静态类名,数组语法适用于条件类名。

绑定静态类名:

<div v-bind:class="{ active: isActive, 'text-success': hasSuccess }"></div>
export default {
data() {
return {
isActive: true,
hasSuccess: false
}
}
}

绑定条件类名数组:

<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
export default {
data() {
return {
isActive: true,
activeClass: 'active',
errorClass: 'text-error'
}
}
}

绑定内联样式:

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
export default {
data() {
return {
activeColor: 'red',
fontSize: 30
}
}
}

绑定样式对象:

<div v-bind:style="styleObject"></div>
export default {
data() {
return {
styleObject: {
color: 'green',
fontSize: '23px'
}
}
}
}

绑定样式数组:

<div v-bind:style="[baseStyles, overridingStyles]"></div>
export default {
data() {
return {
baseStyles: {
color: 'blue',
fontSize: '16px'
},
overridingStyles: {
'font-weight': 'bold'
}
}
}
}

计算属性:

<div v-bind:class="classObject"></div>
export default {
data() {
return {
isActive: true,
errorClass: 'text-error'
}
},
computed: {
classObject() {
return {
active: this.isActive && !this.errorClass,
'text-danger': this.errorClass
}
}
}
}