vue-3-Class 与 Style 绑定

时间:2020-12-16 14:33:57

对象语法:

<div v-bind:class="{ active: isActive }"></div>

<div class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>
data: {
isActive: true,
hasError: false
} <div v-bind:class="classObject"></div>
data: {
isActive: true,
error: null
},
computed: {
classObject: function () {
return {
active: this.isActive && !this.error,
'text-danger': this.error && this.error.type === 'fatal'
}
}
}
数组语法:
data: {
activeClass: 'active',
errorClass: 'text-danger'
} <div v-bind:class="[activeClass, errorClass]"></div> <div v-bind:class="[isActive ? activeClass : '', errorClass]"></div> 在数组语法中使用对象语法:
<div v-bind:class="[{ active: isActive }, errorClass]"></div>

自定义组件上用到 class 属性的时候,这些类将被添加到根元素上面:

Vue.component('my-component', {
template: '<p class="foo bar">Hi</p>'
}) <my-component class="baz boo"></my-component> <my-component v-bind:class="{ active: isActive }"></my-component>
isActive 为 truthy 值,active将被添加
所有值都是真值,除非它们被定义为 falsy (即, 除了false 外,,“”,null,undefined和NaN)。

内联样式:

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data: {
activeColor: 'red',
fontSize:
} <div v-bind:style="styleObject"></div>
data: {
styleObject: {
color: 'red',
fontSize: '13px'
}
} 数组语法可以绑定多个样式对象:
<div v-bind:style="[baseStyles, overridingStyles]"></div>

当 v-bind:style 使用需要特定前缀的 CSS 属性时,如 transform,Vue.js 会自动侦测并添加相应的前缀。