詳解vue.js之綁定class和style的示例代碼
一.綁定Class屬性。
綁定數(shù)據用v-bind:命令,簡寫成:
語法:<div v-bind:class="{ active: isActive }"></div>。class后面的雙引號里接受一個對象字面量/對象引用/數(shù)組作為參數(shù),
這里,{active: isActive}是對象參數(shù),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所對應的函數(shù)必須返回一個對象如下:
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]; } } });
綁定數(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; }
效果,點擊去掉class,會調用removeClass函數(shù),去掉classArray數(shù)組的最后一項,第一次,去掉'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; } } });
除了傳入對象字面量以外,也可以傳入對象引用和數(shù)組給V-bind:style
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue實現(xiàn)動態(tài)顯示與隱藏底部導航的方法分析
這篇文章主要介紹了vue實現(xiàn)動態(tài)顯示與隱藏底部導航的方法,結合實例形式分析了vue.js針對導航隱藏與顯示的路由配置、事件監(jiān)聽等相關操作技巧,需要的朋友可以參考下2019-02-02Vue引入highCharts實現(xiàn)數(shù)據可視化
這篇文章主要為大家詳細介紹了Vue引入highCharts實現(xiàn)數(shù)據可視化,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03Vue3中Watch、Watcheffect、Computed的使用和區(qū)別解析
Watch、Watcheffect、Computed各有優(yōu)劣,選擇使用哪種方法取決于應用場景和需求,watch?適合副作用操作,watchEffect適合簡單的自動副作用管理,computed?適合聲明式的派生狀態(tài)計算,本文通過場景分析Vue3中Watch、Watcheffect、Computed的使用和區(qū)別,感興趣的朋友一起看看吧2024-07-07vue結合g6實現(xiàn)樹級結構(compactBox?緊湊樹)
本文主要介紹了vue結合g6實現(xiàn)樹級結構,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06vue-router的beforeRouteUpdate不觸發(fā)問題
這篇文章主要介紹了vue-router的beforeRouteUpdate不觸發(fā)問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04