詳解vue.js之綁定class和style的示例代碼
一.綁定Class屬性。
綁定數(shù)據(jù)用v-bind:命令,簡(jiǎn)寫成:
語(yǔ)法:<div v-bind:class="{ active: isActive }"></div>。class后面的雙引號(hào)里接受一個(gè)對(duì)象字面量/對(duì)象引用/數(shù)組作為參數(shù),
這里,{active: isActive}是對(duì)象參數(shù),active是class名,isActive是一個(gè)布爾值。下面是一個(gè)例子:
綁定對(duì)象字面量
html:
<div id="classBind">
<span :class="{warning:isWarning,safe:isSafe}" v-on:click="toggle">
狀態(tài):{{alert}}{{isSafe}}
</span>
</div>
//js
var app11=new Vue({
el:'#classBind',
data:{
isWarning:true,
alertList:['紅色警報(bào)','警報(bào)解除'],
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;
}
當(dāng)點(diǎn)擊狀態(tài)文字時(shí),可以切換后面的文字和顏色
//狀態(tài):警報(bào)解除true
//狀態(tài):紅色警報(bào)false
綁定對(duì)象引用
這里綁定的對(duì)象可以寫到Vue實(shí)例的data里面,而在class="classObj ",雙引號(hào)中的class是對(duì)Vue實(shí)例中classObj對(duì)象的引用。classObj可以放在data中或者computed中,如果在computed中,則classObj所對(duì)應(yīng)的函數(shù)必須返回一個(gè)對(duì)象如下:
js:
var app11=new Vue({
el:'#classBind',
data:{
isWarning:true,
alertList:['紅色警報(bào)','警報(bào)解除'],
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];
}
}
});
綁定數(shù)組
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;
}
效果,點(diǎn)擊去掉class,會(huì)調(diào)用removeClass函數(shù),去掉classArray數(shù)組的最后一項(xiàng),第一次,去掉'red',字體顏色由紅變黑,再點(diǎn),去掉'big',字體變小。
二、綁定內(nèi)聯(lián)style
此時(shí)此刻,我一邊看著本頁(yè)旁邊的那個(gè)Vue api文檔學(xué),一邊到這里賣,裝逼的感覺真爽o(^▽^)o
html
<div id="styleBind">
<span :style="{color:theColor,fontSize:theSize+'px'}" @click="bigger">styleBind</span>
</div>
css
這個(gè)不需要css。。。
js
var app12=new Vue({
el:'#styleBind',
data:{
theColor:'red',
theSize:14
},
methods:{
bigger:function(){
this.theSize+=2;
}
}
});
除了傳入對(duì)象字面量以外,也可以傳入對(duì)象引用和數(shù)組給V-bind:style
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue?perfect-scrollbar(特定框架里使用非該框架定制庫(kù)/插件)
vue父組件與子組件之間的數(shù)據(jù)交互方式詳解
element ui的el-input-number修改數(shù)值失效的問題及解決
項(xiàng)目中一鍵添加husky實(shí)現(xiàn)詳解

