1绑定 HTML Class
我们可以传给 v-bind:class 一个对象,以动态地切换 class:
内联样式在模板里
var vm1 = new Vue({
el: "#div1",
data: {
isActive: true,
hasError: true,
}
})
通过浏览器查看,渲染的html结构是:
内联样式不在模板里
var vm2 = new Vue({
el: "#div2",
data: {
class_obj: {
isActive: true,
hasError: true,
}
}
})
渲染为如下的结构:
绑定返回对象的计算属性
var vm3 = new Vue({
el: "#div3",
data: {
isActive: true,
error: true
},
computed: {
classObject: function () {
return {
active: this.isActive && this.error,
'text-danger': this.error
}
}
}
})
渲染的html结构如下:
数组语法
我们可以把一个数组传给 v-bind:class,以应用一个 class 列表:
new Vue({
el: "#div4",
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
})
渲染为
``
###class 列表使用三元表达式
如果你也想根据条件切换列表中的 class,可以用三元表达式:
new Vue({
el: "#div5",
data: {
isActive: true,
activeClass: 'active',
errorClass: 'text-danger'
}
})
渲染为:
```
绑定内联样式v-bind:style
v-bind:style 的对象语法十分直观——看着非常像 CSS,但其实是一个 JavaScript 对象
new Vue({
el: "#div1",
data: {
activeColor: 'red',
fontSize: 30,
msg: "hello vue"
}
})
直接绑定到一个样式对象通常更好,这会让模板更清晰:
new Vue({
el: "#div2",
data: {
msg: "直接绑定到一个样式对象通常更好",
styleObject: {
color: 'red',
fontSize: '23px'
}
}
})
对象语法常常结合返回对象的计算属性使用
new Vue({
el: "#div3",
data: {
msg: "结合返回对象的计算属性使用",
color: 'red',
fontSize: '12px'
},
computed: {
styleObject: function () {
return {color: 'yellow', fontSize: '23px'}
}
}
})
我们可以把一个数组传给 v-bind:class,以应用一个 class 列表
new Vue({
el: "#div4",
data: {
msg: "我是数组绑定方法",
baseStyles: {
color: 'green',
fontSize: '30px'
},
overridingStyles: {
'font-weight': 'bold'
}
}
})