- 對象語法
- 數組語法
一、對象語法
1.1對象語法綁定HTML Class
語法:v-bind:class="{'className1':boolean1,'className2':boolean2}"

1 <style> 2 div{ 3 width: 100px; 4 height: 100px; 5 } 6 .class1{ 7 background-color: #ff0; 8 } 9 .class2{ 10 background-color:#f00; 11 } 12 </style>
1 <div id="example" v-bind:class="{'class1':yellow,'class2':red}" v-on:click="changeColor"></div> 2 <script> 3 var vm = new Vue({ 4 el:"#example", 5 data:{ 6 yellow:true, 7 red:false 8 }, 9 methods:{ 10 changeColor(){ 11 this.yellow = !this.yellow; 12 this.red = !this.red; 13 } 14 } 15 }); 16 </script>
當點擊div時,觸發changeColor方法,數據的值發生變化時,class行間屬性會被切換,下面時觸發效果:
當你看到v-bind:class="{'class1':yellow,'class2':red}"這句代碼是不是就想到了直接使用一個對象替代這個鍵值對的寫法,這當然是可以的:
1 <div id="example" v-bind:class="colorName" v-on:click="changeColor"></div> 2 <script> 3 var vm = new Vue({ 4 el:"#example", 5 data:{ 6 colorName:{ 7 class1:true, 8 class2:false 9 } 10 }, 11 methods:{ 12 changeColor(){ 13 this.colorName.class1 = !this.colorName.class1; 14 this.colorName.class2 = !this.colorName.class2; 15 } 16 } 17 }); 18 </script>
這兩種寫法前一種是空間復雜度大一點,后一種是時間復雜度大一點,怎么應用看具體需求吧。
1.2對象語法綁定HTML Style
語法:v-bind:style="{styleProp1:value1,styleProp2:value2}"
將樣式屬性名和屬性值以鍵值對的形式寫入對象,屬性名采用駝峰書寫模式。
1 <div id="example" v-bind:style="{width:widthVal,height:heightVal,backgroundColor:backColorVal}" v-on:click="changeColor"></div> 2 <script> 3 var vm = new Vue({ 4 el:"#example", 5 data:{ 6 widthVal:'100px', 7 heightVal:'100px', 8 backColorVal:'#ff0' 9 }, 10 methods:{ 11 changeColor(){ 12 this.backColorVal = this.backColorVal == '#ff0' ? '#f00' : '#ff0'; 13 } 14 } 15 }); 16 </script>
實現的效果與HTML Class對象語法實現的一樣,HTML Style對象語法表達式轉換成類名的方式就不展示了。
二、數組語法
2.1數組語法綁定HTML Class
語法:v-bind:class="[classNameKey1,classNameKey2]"
(樣式參考示例1.1的樣式)
1 <div id="example" v-bind:class="[class1,class2]" v-on:click="changeColor"></div> 2 <script> 3 var vm = new Vue({ 4 el:"#example", 5 data:{ 6 class1:'class1', 7 class2:'' 8 }, 9 methods:{ 10 changeColor(){ 11 this.class1 = this.class1 == '' ? 'class1' : ''; 12 this.class2 = this.class2 == '' ? 'class2' : ''; 13 } 14 } 15 }); 16 </script>
2.2數組語法實現HTML Style綁定
語法:v-bind:style="[styleObje1,styleObje2]"
1 <div id="example" v-bind:style="[didiFamily, styleColo]" v-on:click="changeColor" ref="example"></div> 2 <script> 3 var vm = new Vue({ 4 el:"#example", 5 data:{ 6 didiFamily:{ 7 width:'100px', 8 height:'100px' 9 }, 10 styleColo:{ 11 backgroundColor:'#ff0' 12 } 13 }, 14 methods:{ 15 changeColor(){ 16 return this.styleColo.backgroundColor = this.styleColo.backgroundColor == '#ff0' ? '#f00' : '#ff0'; 17 } 18 } 19 }); 20 </script>