Vue学习—Class与Style绑定

class和style绑定,使用v-bind处理,并在v-bind上对表达式的结果类型进行了扩展,除了字符串之外还可以是对象或数组。

一、class绑定

1、对象
(1)v-bind的class可以与普通的class属性共存
(2)v-bind的class可以将对象写入到class中
(3)v-bind的class可以将对象写入到data中,并在class中进行调用
(4)返回对象的计算属性

(1)(2)

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

如下的data:

data:{
    isActive:true,
    hasError:false
}

渲染为:

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

(3)

<div v-bind:class="classObject"></div>
data:{
    classObject:{
        active:true,
        'text-danger':false
    }
}

(4)

<div v-bind:class="classObject"></div>
data:{
    isActive:true,
    error:null
},
computed:{
    classObject:fucntion(){
        return{
            active:this.isActive && !this.error,
            'text-danger':this.error && this.error.type==='fatal'
        }
    }
}
2、数组语法
<div v-bind:class="[activeClass,errorClass]">
data:{
    activeClass:'active',
    errorClass='text-danger'
}

渲染为:

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

也可以根据条件切换列表中的class,可以使用三元表达式。

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

此例始终添加errorClass但是只有在isActive为true时才添加activeClass。
也可以在数组中使用对象语法:

<div v-bind:class="[{active:isActive},errorClass]"></div>
3、用在组件上

在组件上使用class属性,不会被实例所覆盖。

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

在使用时添加class:

<my-component class="bat boo"></my-component>

html被最终渲染为:

<p class="foo bar bag boo">Hi</p>

同样也适用于v-bind形式绑定的class:

<my-component v-bind:class="{active:idActive}"></my-component>

当isActive为true时,html将被渲染为:

<p class="foo bar active">Hi</p>

二、绑定内联样式

1、对象语法

和css类似,一般采用驼峰式命名:

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

绑定到一个样式对象上:

<div v-bind:style="styleObject"></div>
data:{
    styleObject:{
        color:'red',
        font-size:'13px'
    }
}
2、数组语法

v-bind:style的数组语法可以将多个样式对象应用到一个元素上:

<div v-bind:style="[baseStyle,overringStyles]"></div>
3、自动添加前缀

当v-bind:style使用需要特定前缀的css属性时,如transform,vue.js会自动侦测并添加相应的前缀。

4、多重值

从 2.3 开始可以为 style 绑定中的属性提供一个包含多个值的数组,常用于提供多个带前缀的值:

<div :style="{ display: ["-webkit-box", "-ms-flexbox", "flex"] }">
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值