vue给对象添加v-html,vue学习(绑定class、v-bind:style(对象语法、数组语法))

1绑定 HTML Class

我们可以传给 v-bind:class 一个对象,以动态地切换 class:

内联样式在模板里

var vm1 = new Vue({

el: "#div1",

data: {

isActive: true,

hasError: true,

}

})

通过浏览器查看,渲染的html结构是:

内联样式不在模板里

var vm2 = new Vue({

el: "#div2",

data: {

class_obj: {

isActive: true,

hasError: true,

}

}

})

渲染为如下的结构:

绑定返回对象的计算属性

var vm3 = new Vue({

el: "#div3",

data: {

isActive: true,

error: true

},

computed: {

classObject: function () {

return {

active: this.isActive && this.error,

'text-danger': this.error

}

}

}

})

渲染的html结构如下:

数组语法

我们可以把一个数组传给 v-bind:class,以应用一个 class 列表:

new Vue({

el: "#div4",

data: {

activeClass: 'active',

errorClass: 'text-danger'

}

})

渲染为

``

###class 列表使用三元表达式

如果你也想根据条件切换列表中的 class,可以用三元表达式:

new Vue({

el: "#div5",

data: {

isActive: true,

activeClass: 'active',

errorClass: 'text-danger'

}

})

渲染为:

```

绑定内联样式v-bind:style

v-bind:style 的对象语法十分直观——看着非常像 CSS,但其实是一个 JavaScript 对象

{{ msg }}

new Vue({

el: "#div1",

data: {

activeColor: 'red',

fontSize: 30,

msg: "hello vue"

}

})

直接绑定到一个样式对象通常更好,这会让模板更清晰:

{{ msg }}

new Vue({

el: "#div2",

data: {

msg: "直接绑定到一个样式对象通常更好",

styleObject: {

color: 'red',

fontSize: '23px'

}

}

})

对象语法常常结合返回对象的计算属性使用

{{ msg }}

new Vue({

el: "#div3",

data: {

msg: "结合返回对象的计算属性使用",

color: 'red',

fontSize: '12px'

},

computed: {

styleObject: function () {

return {color: 'yellow', fontSize: '23px'}

}

}

})

我们可以把一个数组传给 v-bind:class,以应用一个 class 列表

{{ msg }}

new Vue({

el: "#div4",

data: {

msg: "我是数组绑定方法",

baseStyles: {

color: 'green',

fontSize: '30px'

},

overridingStyles: {

'font-weight': 'bold'

}

}

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值