数据绑定一个常见需求是操作元素的 class 列表和它的内联样式。因为它们都是属性 ,我们可以用v-bind 处理它们:只需要计算出表达式最终的字符串。不过,字符串拼接麻烦又易错。因此,在 v-bind 用于 class 和 style 时, vue.js 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。
我们可以传给 v-bind:class 一个对象,以动态地切换 class 。
<div v-bind:class="{ active: isactive }"></div>
上面的语法表示 classactive 的更新将取决于数据属性 isactive 是否为真值 。
我们也可以在对象中传入更多属性用来动态切换多个 class 。此外, v-bind:class 指令可以与普通的 class 属性共存。如下模板:
<div class="static"
v-bind:class="{ active: isactive, 'text-danger': haserror }">
</div>
如下 data:
data: {
isactive: true,
haserror: false
}
渲染为:
<div class="static active"></div>
当 isactive 或者 haserror 变化时,class 列表将相应地更新。例如,如果 haserror的值为 true , class列表将变为 "static active text-danger"。
你也可以直接绑定数据里的一个对象:
<div v-bind:class="classobject"></div>
data: {
classobject: {
active: true,
'text-danger': 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',
}
}
}
我们可以把一个数组传给 v-bind:class ,以应用一个 class 列表:
<div v-bind:class="[activeclass, errorclass]">
data: {
activeclass: 'active',
errorclass: 'text-danger'
}
渲染为:
div class="active text-danger"></div>
如果你也想根据条件切换列表中的 class ,可以用三元表达式:
<div v-bind:class="[isactive ? activeclass : '', errorclass]">
此例始终添加 errorclass ,但是只有在 isactive 是 true 时添加 activeclass 。
不过,当有多个条件 class 时这样写有些繁琐。可以在数组语法中使用对象语法:
<div v-bind:class="[{ active: isactive }, errorclass]">
本小节的内容是假设你已经对 vue 组件 有一定的了解。当然你也可以跳过这里,稍后再回过头来看。
当你在一个定制的组件上用到 class 属性的时候,这些类将被添加到根元素上面,这个元素上已经存在的类不会被覆盖。
例如,如果你声明了这个组件:
vue.component('my-component', {
template: '<p class="foo bar">hi</p>'
})
然后在使用它的时候添加一些类:
<my-component class="baz boo"></my-component>
html 最终将被渲染成为:
<p class="foo bar baz boo">hi</p>
同样的适用于绑定 html class :
<my-component v-bind:class="{ active: isactive }"></my-component>
当 isactive 为 true 的时候,html 将被渲染成为:
<div class="foo bar active"></div>
v-bind:style 的对象语法十分直观——看着非常像 css ,其实它是一个 javascript 对象。 css 属性名可以用驼峰式(camelcase)或短横分隔命名(kebab-case):
<div v-bind:style="{ color: activecolor, fontsize: fontsize + 'px' }"></div>
data: {
activecolor: 'red',
fontsize: 30
}
直接绑定到一个样式对象通常更好,让模板更清晰:
<div v-bind:style="styleobject"></div>
data: {
styleobject: {
color: 'red',
fontsize: '13px'
}
}
同样的,对象语法常常结合返回对象的计算属性使用。
v-bind:style 的数组语法可以将多个样式对象应用到一个元素上:
<div v-bind:style="[basestyles, overridingstyles]">
当 v-bind:style 使用需要特定前缀的 css 属性时,如 transform ,vue.js 会自动侦测并添加相应的前缀。