Vue对class的操作不会覆盖原标签带有的class属性,而是追加
1. 对象语法内联定义
//active为要添加的class,isActive值为真就会保留,为假active就没了
<div v-bind:class="{ active: isActive }"></div>
2.对象语法非内联定义
//绑定属性classObject
<div v-bind:class="classObject"></div>
//在vue中声明classObject属性
data: {
classObject: {
active: true,
'text-danger': false
}
}
//这里用了简单的data中声明属性,如果愿意也可以在computed计算属性中声明
3.数组的方式
//activeClass和errorClass为vue的俩个属性
<div v-bind:class="[activeClass, errorClass]"></div>
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
4.数组中放表达式
//errorClass一直有,activeClass看三元运算符结果
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
5.对象和数组混用
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
6.组件
Vue.component('my-component', {
template: '<p class="foo bar">Hi</p>'
})
<my-component class="baz boo"></my-component>
<my-component v-bind:class="{ active: isActive }"></my-component>
2种方式都会class共存不要方