在v-bind
用于class
和style
时,Vue做了专门的增强。表达式结果的类型除了字符串
之外、还可以是对象
或数组
。
绑定HTML Class
我们可以传给v-bind:class
一个对象,以动态的切换class:
此语法表示,
active
这个class存在与否取决于属性isActive
的真假值。
<div v-bind:class="{ active: isActive }"></div>
data(){
return{
isActive:true,
}
}
<style>
.active{
color: red;
}
</style>
也可以在对象中传入多个字段来动态切换多个class,此外v-bind:class
指令也可以与普通的class属性共存。
//注意:如果定义的样式有中划线,此处绑定的class必须使用引号包裹。
<div
class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>
data() {
return {
isActive:false,
hasError:true
}
}
<style>
.active{
color: red;
}
.text-danger{
font-size: 30px;
}
</style>
结果渲染为:
<div class="static text-danger"></div>
也可以直接绑定一个对象
<div :class="classObj">我的div</div>
//属性
data(){
return {
classObj:{
active:true,
'text-danger':true
}
}
},
//样式
<style>
.active{
color: red;
}
.text-danger{
font-size: 30px;
}
</style>
也可以绑定一个返回对象的计算属性
<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]"></div>
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
<style>
.active{
color: red;
}
.text-danger{
font-size: 30px;
}
</style>
渲染结果为:
<div class="active text-danger"></div>
如果想根据条件切换列表中的class,可以使用三元表达式:
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
当有多个条件class时,以上的写法有些繁琐,所以在数组语法中也可以使用对象语法:
<div v-bind:class="[{active:isActive},errClass]">我的div</div>
//属性
data() {
return {
isActive:true,
errClass:'errorClass'
}
},
//样式
<style>
.active{
color: red;
}
.errorClass{
background-color: #d2b600;
}
</style>
在自定义组件上使用class属性时,这些class将被添加到改组件的根元素上面,这个元素上已经存在的class不会被覆盖。
如下声明一个组件:
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>
对于带数据绑定的class也同样适用:
<my-component v-bind:class="{ active: isActive }"></my-component>
对上面的语句,当isActive
为true时,HTML将被渲染为:
<p class="foo bar active">Hi</p>
绑定内联样式
v-bind:style
的对象语法很像CSS,但其实是一个js对象。CSS的属性名可以用驼峰式或者短横线(记得用引号括起来)命名。
<div v-bind:style="{color:activeColor,fontSize:fontSize + 'px'}">我的div</div>
//属性
data() {
return {
activeColor:'red',
fontSize:30
}
},
直接绑定到一个样式对象通常更好,这会让模板更清晰:
<div v-bind:style="styleObject"></div>
//属性对象
data: {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
v-bind:style
的数组语法可以将多个样式对象应用到同一个元素上:
<div v-bind:style="[titleCols,titleS]">我的div</div>
//样式属性
data() {
return {
titleCols:{
color:'green'
},
titleS:{
fontSize:'45px'
}
}
},
v-bind:style
使用需要添加的CSS属性时,如
transform
,Vue会自动侦测并添加相应的前缀。
2.3.0后,可以为style
绑定中的属性提供一个包含多个值的数组,常用于提供多个带前缀的值,如:
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
这样写只会渲染数组中最后一个被浏览器支持的值,在本例中,如果浏览器支持不带浏览器前缀的flexbox,那么就只会渲染display:flex
。
网友评论