vue的动态样式绑定class与style

class属性绑定

v-bind:class 设置为对象

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

<script>
new Vue({
  el: '#app',
  data: {
    isActive: true,
	hasError: true
  }
})
</script>

运行后,以上div class变成

<div class="static active text-danger"></div>

v-bind:class 直接绑定数据里的一个对象

<div id="app">
  <div v-bind:class="classObject"></div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    classObject: {
      active: true,
      'text-danger': true
    }
  }
})
</script>

运行后,以上div class变成

<div class="active text-danger"></div>

v-bind:class 绑定计算属性

<div id="app">
  <div v-bind:class="classObject"></div>
</div>
<script>

new Vue({
  el: '#app',
  data: {
    isActive: true,
    error: {
      value: true,
      type: 'fatal'
    }
  },
  computed: {
    classObject: function () {
      return {
        base: true,
        active: this.isActive,
        'text-danger': this.error.value && this.error.type === 'aaa',
      }
    }
  }
})
</script>

运行后,以上div class变成

<div class="base active"></div>

v-bind:class 绑定数组

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

<script>
new Vue({
  el: '#app',
  data: {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})
</script>

运行后,以上div class变成

<div class="active text-danger"></div>

v-bind:class 绑定三元表达式

<div id="app">
    <div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>
</div><script>
new Vue({
  el: '#app',
  data: {
    isActive: true,
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})
</script>

运行后,以上div class变成

<div class="active text-danger"></div>

style属性绑定(内联样式)

以下实例 div style 为:

<div style="color: green; font-size: 30px;">菜鸟教程</div>

v-bind:style 绑定对象

<div id="app">
	<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">菜鸟教程</div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    activeColor: 'green',
	fontSize: 30
  }
})
</script>

v-bind:style 绑定数据里的样式对象

<div id="app">
  <div v-bind:style="styleObject">菜鸟教程</div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    styleObject: {
      color: 'green',
      fontSize: '30px'
    }
  }
})
</script>

v-bind:style 绑定数组

<div id="app">
  <div v-bind:style="[baseStyles, overridingStyles]">菜鸟教程</div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    baseStyles: {
      color: 'green'
      
    },
	overridingStyles: {
      'fontSize: '30px'
    }
  }
})
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值