vue.js之綁定class和style


一.綁定Class屬性。

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

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

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

綁定對象字面量

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:

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

當點擊狀態文字時,可以切換后面的文字和顏色

//狀態:警報解除true

//狀態:紅色警報false

綁定對象引用

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

js:

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',字體變小。

二、綁定內聯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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM