Vue动态class

注意在自定义组件上绑定class会添加到该组件的根元素上面

1.对象语法

  • 传入class对象
  • v-bind:class 指令也可以与普通的 class attribute 共存
  • 可以动态修改class的值
  • 可以绑定一个计算数据来实现

1.传入class对象

    <script src="./vue.js"></script>
    <div id="app" v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>
    <script>
        new Vue({
            el:"#app",
            data(){
                return {
                    isActive:true,
                    hasError:true
                }
            }
        });

2. v-bind:class 指令也可以与普通的 class attribute 共存

<div id="app" class="checked" v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>

 

3.可以动态修改class的值

    <script src="./vue.js"></script>
    <div id="app" class="checked" @click="changeClass" v-bind:class="{ active: isActive, 'text-danger': hasError }">这是测试div</div>
    <script>
        new Vue({
            el:"#app",
            data(){
                return {
                    isActive:true,
                    hasError:true
                }
            },
            methods:{
                changeClass(){
                    this.isActive = !this.isActive;
                }
            }
        });

4.可以绑定一个计算数据来实现

data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

2.数组语法

  • 传入一个数组
  • 可以使用三元表达式
  • 数组中也可以使用对象语法

传入一个数组

div v-bind:class="[activeClass, errorClass]"></div>

可以使用三元表达式

<div v-bind:class="[isActive ? 'active' : '', 'text-danger']"></div>

数组中也可以使用对象语法

<div v-bind:class="[{ active: isActive }, 'text-danger']"></div>

3.绑定内联样式

v-bind:style 的对象语法十分直观——看着非常像 CSS,但其实是一个 JavaScript 对象。CSS property 名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用引号括起来) 来命名:

<div v-bind:style="{ color: red, fontSize: 30 + 'px' }"></div>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值