標籤:remove code att name 而在 雙引號 iss color 對象引用
一.綁定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‘,字型變小。
vue.js之綁定class和style