Vue学习笔记----v-bind:class和style绑定

1.动态绑定class

1.1对象语法

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

data: {
  isActive: true
}

active : class样式名
isActive : data属性
v-bind:class ---- 类似于小程序的class嵌套wx:if通过data属性的值来动态的添加或删除样式

 

1.2计算语法

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

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

computed是vue.js的计算属性
通过示例可以知道,classObject通过vue.jsbind进行了绑定,并通过computed计算属性进行控制

 

1.3数组语法

<div v-bind:class="[activeClass, errorClass]"></div>
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>  -- 三元表达式写法
<div v-bind:class="[{ active: isActive }, errorClass]"></div>    -- 嵌套对象写法

data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

示例中activeClasserrorClass都是虚化的class其实是data的属性,属性值active才是真正的class样式

 

1.4组件嵌套

自定义组件my-component
Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})

<my-component class="baz boo"></my-component> -- 直接添加class
<my-component v-bind:class="{ active: isActive }"></my-component>  -- 动态绑定class

渲染效果
<p class="foo bar baz boo">Hi</p>

 

动态绑定style

1.1对象语法

 -- 属性赋值
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

data: {
  activeColor: 'red',
  fontSize: 30
}

-- 对象
<div v-bind:style="styleObject"></div>

data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}

1.2数组语法

<div v-bind:style="[baseStyles, overridingStyles]"></div>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值