vue.js學習筆記之綁定style樣式和class列表
數據綁定一個常見需求是操作元素的 class 列表和它的內聯(lián)樣式。因為它們都是 attribute,我們可以用 v-bind 處理它們:只需要計算出表達式最終的字符串。不過,字符串拼接麻煩又易錯。因此,在 v-bind 用于 class 和 style 時,Vue.js 專門增強了它。表達式的結果類型除了字符串之外,還可以是對象或數組。
一.綁定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">
狀態(tài):{{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;
}
當點擊狀態(tài)文字時,可以切換后面的文字和顏色
//狀態(tài):警報解除true
//狀態(tài):紅色警報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',字體變小。
二、綁定內聯(lián)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
以上所述是小編給大家介紹的vue.js學習筆記之綁定style和class,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
解決vue axios的封裝 請求狀態(tài)的錯誤提示問題
今天小編就為大家分享一篇解決vue axios的封裝 請求狀態(tài)的錯誤提示問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09

