1.绑定Html Class(在 v-bind
用于 class
和 style
时, Vue.js 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组)
1.1对象语法
传给v-bind:class一个对象,可以动态切换class。<div v-bind:class="{ active: isActive }"></div>
v-bind指令可以和普通class共存,如下渲染结果为<div class="static active"></div>:
<div class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>
data: {
isActive: true,
hasError: false
}
v-bind也可以绑定计算属性,如下绑定计算属性。
<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',
}
}
}
1.2数组语法
我们可以把一个数组传给
v-bind:class
,以应用一个 class 列表,下面渲染为<div class="active text-danger"></div>:<div v-bind:class="[activeClass, errorClass]">
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
1.3用在组件上
例如,如果你声明了这个组件:
Vue.component('my-component', {
template: '<p class="foo bar">Hi</p>'
})
然后在使用它的时候添加一些 class:<my-component class="baz boo"></my-component>
HTML 最终将被渲染成为:<p class="foo bar baz boo">Hi</p>
2.绑定内联样式
2.1对象语法
v-bind:style的对象语法十分直观,看起来很像css。<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
但是通常会绑定一个样式对象<div v-bind:style="styleObject"></div>
data: {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
2.2数组语法
v-bind:style
的数组语法可以将多个样式对象应用到一个元素上:<div v-bind:style="[baseStyles, overridingStyles]">2.3自动添加前缀
当
v-bind:style
使用需要特定前缀的 CSS 属性时,如 transform
,Vue.js 会自动侦测并添加相应的前缀。