一、绑定 HTML Class
1、对象语法:效果都是一样的几种方式
方式1:采用 对象 的方式
<!--方式1-->
<div id="test" class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>
var test = new Vue({
el: '#test',
data: {
isActive: true,
hasError: true
}
})
方式2:采用 对象不内联在模版里 的方式
<!--方式2-->
<div id="test1" v-bind:class="classObject"></div>
var test1 = new Vue({
el: '#test1',
data: {
classObject: {
active: true,
'text-danger': false
}
}
})
方式3:采用 计算属性 的方式
<!--方式3-->
<div id="test2" v-bind:class="classObject"></div>
var test2 = new Vue({
el: '#test2',
data: {
isActive: true,
error: null
},
conputed: {
classObject: function() {
return {
active: this.isActive && this.error,
'test-danger': this.error && this.error.type == 'fatal'
}
}
}
})
2、数组语法:与 对象语法 一样的效果
把一个数组传给 v-bind:class,来应用一个 class 列表:
<div v-bind:class="[activeClass, errorClass]"></div>
var test = new Vue({
el: '#test',
data: {
activeClass: 'active',
errorClass: 'test-danger'
}
})
渲染后的结果是:
<div class="active text-danger"></div>
如果想 根据条件切换 列表中的 class,可以用三元表达式,不过这样写会始终添加 errorClass,但是还有在 isActive 是 truthy 时才添加 activeClass:
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
如果,有多个条件 class 时这样写稍微繁琐,所以在数组语法中也可以这样使用对象语法结合:
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
3、用在组件上:
当一个自定义组件上使用 class property 时,这些 class 将被添加到该组件的根元素上,这个元素上已经存在的 class 不会被覆盖;
例如:声明了以下组件:
<my-component class="baz boo"></my-component>
Vue.component('my-component', {
template: '<p class="foo bar">Hi</p>'
})
那么 HTML 中将被渲染成:
<p class="foo bar baz boo">Hi</p>
对于 带数据绑定 class 也可以适用:
<my-component v-bind:class="{ active: isActive }"></my-component>
Vue.component('my-component', {
template: '<p class="foo bar">Hi</p>'
})
那么 HTML 中,当 isActive 为 truthy 时,渲染为:
<p class="foo bar active">Hi</p>
二、绑定内联 样式
1、对象语法上:
v-bind:style 的对象语法十分直观,看着非常像 CSS,但其实是一个 JavaScript 对象。
CSS property 名可以用 驼峰式 或 短横线分隔 来命名:
方式1:直接对象外嵌入
<div id="test1" v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">
对象样式1
</div>
var test1 = new Vue({
el: '#test1',
data: {
activeColor: 'red',
fontSize: 30
}
})
方式2:通过对象内嵌入
<div id="test2" v-bind:style="styleObject">
对象样式2
</div>
var test2 = new Vue({
el: '#test2',
data: {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
})
方式2:通过 计算属性 嵌入
<div id="test3" v-bind:style="styleObject">
对象样式3 计算属性
</div>
var test3 = new Vue({
el: '#test3',
data: {
activeColor: 'blue',
size: '50px'
},
computed: {
styleObject: function() {
return { color: this.activeColor, fontSize: this.size }
}
}
})
结果:

2、数组语法上:
v-bind:style 的数组语法可以将多个样式对象应用到同一个元素上:
<div id="test" v-bind:style="[baseStyles, overridingStyles]">
数组样式
</div>
var test = new Vue({
el: '#test',
data: {
baseStyles: {
color: 'red'
},
overridingStyles: {
fontSize: '23px'
}
}
})
结果为:

浙公网安备 33010602011771号