v-bind绑定css

1.绑定class

直接上官网的例子:

1
<div :class="classObject"></div>

首先,该div绑定了一个数据对象为classobject

然后将这个对象通过计算属性进行改写

1
2
3
4
5
6
7
8
9
10
11
12
data: {
isActive: true,
error: null
},
computed: {
classObject: function () {
return {
active: this.isActive && !this.error,
'text-danger': this.error && this.error.type === 'fatal'
}
}
}

data中存放两个数据:isActiveerror,这两个数据的状态决定了下面计算属性的结果

computed中对classobject进行定义,他的返回值有==两种情况==:

  • isActive为真,且error也为真时,会返回active

  • 这个可以看上文

    这个例子的应用在todomvc中有详细的应用,通过数据状态来修改css

2.绑定style

1
<div v-bind:style="styleObject"></div>
1
2
3
4
5
6
data: {
styleObject: {
color: 'red',
fontSize: '13px'
}
}