Vue操作Class

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>'
})
  1. <my-component class="baz boo"></my-component>
  2. <my-component v-bind:class="{ active: isActive }"></my-component>
    2种方式都会class共存不要方

方式很多比较花里胡哨,目的都是相同的那就是把class值加上去,个人比较喜欢第二种方式,不喜勿喷

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值