内容提要:
- 绑定HTML classes的语法:对象语法、数组语法、在组件上的使用
- 绑定内联样式的语法:对象语法、数组语法、自动加前缀与多个值的使用
对于数据绑定的一种常见需要是操作元素的类列表和它的内联样式。由于它们都是属性,我们能用v-bind
管理他们。我们仅仅需要使用我们的表达式计算最后的字符串。然而,字符串串联的干扰是令人烦恼和易于出错的。因为这个原因,当v-bind
用于class
和style
的时候Vue提供了特定的改进手段。除了字符串,表达式也可以使用对象和数组作计算。
绑定HTML类
对象语法
我们能传递一个对象给v-bind:class
去动态的触发类:
<div v-bind:class="{active: isActive}"></div>
以上语法意味着active
类的存在与否取决于isActive
的真实性。
通过在对象中使用多个字段你能够使多个类被触发。另外,v-bind:class
指令也能够与纯class
属性共存于一个标签。
<div class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>
如果是以下数据:
data:{
isActive:ture,
hasError: false
}
它将被渲染为如下形式:
<div class="static active"></div>
当isActive
或hasError
改变的时候,类的列表会相应的更新。例如,如果hasError
变成true
,类列表将变成“static active text-danger”
.
绑定对象不必在行内:
<div v-bind:class="classObject"></div>
data: {
classObject: {
active: true
'text-danger': false
}
}
这将返回相同的结果,我们也能够绑定一个computed property 返回一个对象。这是一种常用的和强大的模式:
<div v-bind:class="classOjbect"></div>
data: {
isActive: true,
error: null
},
computed: {
classObject: function() {
return {
active: this.isActive && !this.error,
'text-danger': this.error && this.errror.type === 'fatal'
}
}
}
数组语法
我们能够传递一个数组给v-bind:class
去使用一个类列表:
<div v-bind:class="[activeClass, errorClass]"></div>
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
它将被渲染为:
<div class="active text-danger"></div>
如果你想根据列表的条件去触发一个类,你可以使用三元表达式:
<div v-bind:class="[isActive ? activeClass : '',errorClass]"></div>
这将总是请求errorClass
,但是仅仅isActive
为真时请求activeClass
。
然而,如果有多个条件的class可能有一点长,这就是为什么在数组语法内使用对象语法:
<div v-bind:class="[{active: isActive}, errorClass]"></div>
组件中使用
这部分内容假定你有 Vue Components知识。你可以选择跳过这节稍后再回来。
当你在自定义的组件上使用class
属性的时候,这些classes将被添加到组件的根元素。这个元素上已经存在的classes将不会被覆盖。
例如,如果你声明了这个组件:
Vue.component('my-component',{
template: '<p class="foo bar">Hi</p>'
})
当使用它的时候添加一些classes:
<my-component class="baz boo"></my-component>
HTML将被渲染成:
<p class="foo bar baz boo">Hi</p>
class绑定也是同样的道理:
<my-component v-bind:class="{ active: isActive }"></my-component>
当isActive
为真的时候,HTML将被渲染成:
<p class="foo bar active">Hi</p>
创建内联样式
对象语法
v-bind:style
对象语法相当简单-它看起来和CSS很像,只是它是JavaScript对象。你即可以使用驼峰或短横线隔开(用单引号括起来)来命名CSS属性:
<div v-bind:style="{color: activeColor, 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]"></div>
自动加前缀
当你使用一个CSS属性在v-bind:style中请求vendor prefixes ,例如transform
,Vue将自动寻找和添加合适的前缀给到所使用的样式。
多个值
2.3.0+
从2.3.0+开始你能提供一个数组的多个值给到一个样式属性,例如:
<div v-bind:style="{ display: ['-webkit-bix', '-ms-flexbox','flex'] }"></div>
这里对于支持的浏览器仅仅渲染最后一个值。在这个例子里,它将渲染为display:flex
用于支持非前缀版本的flexbox的浏览器。