Vue.js 樣式綁定

1.對象語法

(1)使用v-bind爲class綁定一個對象,對象的key爲樣式名,key的值爲布爾值。若是爲true則添加這個類名,爲false則移除這個類名。
這個方法適用class類名肯定,但可能添加,也可能不添加的情形css

.active{
    color:red;
}

<div id="app">
    <p :class="{active:isActive}">今天禮拜四</p>
</div>
var vm = new Vue({
    el:'#app',
    data:{
        isActive:true
    }
})

(2)添加多個類名:添加多個鍵值對便可
注意:添加多個類名時,key最好加上 引號 否則會報錯html

<p :class="{active:isActive,'text-center':isCenter}">今天禮拜四</p>

(3)v-bind:class接收一個對象,能夠傳遞一個對象值給他,也能夠用方法或者 計算屬性返回一個對象給他均可以vue

computed:{
  classObject:function(){
       return {active:this.isActive,'text-center':this.isCenter}
  }
}
<p :class="classObject">今天禮拜四</p>

2.數組語法

能夠把一個數組傳給 v-bind:class,以應用一個 class 列表
語法:v-bind:class="[]"
數組元素能夠是class類名,也能夠是vue定義的變量數組

//直接使用類名
<p :class="['active','text-center']">今天禮拜四</p>
//使用vue定義的變量
<p :class="[activeClass,centerClass]">今天禮拜四</p>
data:{
    activeClass:'active',
    centerClass:'text-center'
}

渲染結果:app

<p class="active text-center">今天禮拜四</p>

3.綁定內聯樣式

其實就是使用v-bind給style屬性綁定值.
(1)對象語法:適合給單個css屬性賦值。
語法:v-bind:style="{css屬性,屬性值}"
(2)數組語法:適合給2個或2個以上的css屬性賦值
語法:v-bind:style="[{css屬性,屬性值},{css屬性,屬性值}]"
注意:對象中的key不能有 - 這樣的字符,text-align要寫成textAlignthis

<!-- html語法 -->
<h1 style="color:red">html語法</h1>
<!-- 對象語法 css屬性值爲字符串-->
<h1 :style="{color:'green'}">對象語法</h1>
<!-- 對象語法 css屬性值爲vue定義的變量-->
<h1 :style="{color:myColor}">對象語法</h1>
<!-- 數組語法 -->
<h1 :style="[{color:'green'},{textAlign:'center'}]">數組語法</h1>

渲染結果:code

<h1 style="color: red;">html語法</h1>
<h1 style="color: green;">對象語法</h1>
<h1 style="color: blue;">對象語法</h1>
<h1 style="color: green; text-align: center;">數組語法</h1>

4.子組件標籤上的class類

若是組件自己已經有class類,而調用組件的時候又給他綁定了新的class類,那麼他們不會覆蓋,而是會疊加在一塊兒htm

//父組件
<child :class="{box:flag}"></Child>
//子組件
<div :class="{child:flag}">
    <p>我是子組件</p>
</div>

渲染結果:對象

<div class="child box"><p>我是子組件1</p></div>
相關文章
相關標籤/搜索