vue.js之綁定class和style

一.綁定Class屬性。

綁定數據用v-bind:命令,簡寫成:css

語法<div v-bind:class="{ active: isActive }"></div>。class後面的雙引號裏接受一個對象字面量/對象引用/數組做爲參數,html

這裏,{active: isActive}是對象參數,active是class名,isActive是一個布爾值。下面是一個例子:api

綁定對象字面量

html:數組

<div id="classBind">
    <span :class="{warning:isWarning,safe:isSafe}" v-on:click="toggle">
    狀態:{{alert}}{{isSafe}}
    </span>
</div>
//js
var app11=new Vue({ el:'#classBind', data:{ isWarning:true, alertList:['紅色警報','警報解除'], alert:'' }, computed:{ isSafe:function(){ return !this.isWarning; } }, methods:{ toggle:function(){ this.isWarning=!this.isWarning; this.alert= this.isWarning?this.alertList[0]:this.alertList[1]; } } });

css:app

.warning{
    color:#f24;
}
.safe{
    color:#42b983;
}

當點擊狀態文字時,能夠切換後面的文字和顏色函數

//狀態:警報解除true字體

//狀態:紅色警報falsethis

綁定對象引用

這裏綁定的對象能夠寫到Vue實例的data裏面,而在class="classObj ",雙引號中的class是對Vue實例中classObj對象的引用。classObj能夠放在data中或者computed中,若是在computed中,則classObj所對應的函數必須返回一個對象以下:spa

js:code

var app11=new Vue({
    el:'#classBind',
    data:{
        isWarning:true,
        alertList:['紅色警報','警報解除'],
        alert:''
    },
    computed: {
        isSafe: function () {
            return !this.isWarning;
        },
        classObj:function(){
            return {
                warning: this.isWarning,
                safe:this.isSafe
            }
        }
    },
    methods:{
        toggle:function(){
            this.isWarning=!this.isWarning;
            this.alert= this.isWarning?this.alertList[0]:this.alertList[1];
        }
    }

});

綁定數組

html:

<div v-bind:class="classArray" @click="removeClass()">去掉class</div>

 

js

data: {
classArray:["big",'red']
}
methods:{
removeClass:function(){
  this.classArray.pop();
}
}

css:

.big{
    font-size:2rem;
}
.red{
     color:red;    
}

效果,點擊去掉class,會調用removeClass函數,去掉classArray數組的最後一項,第一次,去掉'red',字體顏色由紅變黑,再點,去掉'big',字體變小。

2、綁定內聯style

此時此刻,我一邊看着本頁旁邊的那個Vue api文檔學,一邊到這裏賣,裝逼的感受真爽o(^▽^)o

html

<div id="styleBind">
    <span :style="{color:theColor,fontSize:theSize+'px'}" @click="bigger">styleBind</span>
</div>

css

這個不須要css。。。

js

var app12=new Vue({
    el:'#styleBind',
    data:{
        theColor:'red',
        theSize:14
    },
    methods:{
        bigger:function(){
            this.theSize+=2;
        }
    }

});

除了傳入對象字面量之外,也能夠傳入對象引用和數組給V-bind:style

相關文章
相關標籤/搜索