1.v-bind:绑定class基本语法
- 对象语法
- 数组语法
这两种语法都可以直接赋值或者用函数返回值
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .active { 8 color: red; 9 } 10 </style> 11 </head> 12 <body> 13 14 <div id="vue"> 15 <!--第一个class是固定绑定,第二个使用vue通过键值对绑定--> 16 <!--1.Vue绑定class对象语法:{{css样式名称:vue中的数据变量}}--> 17 <h2 class="title" :class="{active: isActive, line: isLine}">{{message}}</h2> 18 <h2 class="title" :class="getClass1()">{{message}}</h2> 19 <button @click="btnClick">button</button> 20 21 <!--2.Vue绑定class数组语法--> 22 <h2 class="title" :class="[test1, test2]">{{message}}</h2> 23 <h2 class="title" :class="getClass2()">{{message}}</h2> 24 </div> 25 26 <!--导入Vue.js--> 27 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> 28 <script type="text/javascript"> 29 let vm = new Vue({ 30 el: '#vue', 31 data: { 32 message: "test vue", 33 isActive: true, 34 isLine: true, 35 test1: "test1", 36 test2: "test2" 37 }, 38 methods: { 39 btnClick: function () { 40 this.isActive = !this.isActive; 41 }, 42 getClass1: function () { 43 return { 44 active: this.isActive, 45 line: this.isLine 46 } 47 }, 48 getClass2: function () { 49 return [this.test1, this.test2]; 50 } 51 52 } 53 54 55 }); 56 </script> 57 </body> 58 </html>
2.v-bind:绑定style基本语法
- 对象语法
- 数组语法
注:v-bind绑定CSS属性写法
- 驼峰式:fontSize
- 短横线分隔:font-size
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .active { 8 color: red; 9 } 10 </style> 11 </head> 12 <body> 13 14 <div id="vue"> 15 16 <!--1.v-bind绑定style的对象语法--> 17 <!--'50px' 必须加单引号,否则解析为一个变量--> 18 <h2 :style="{fontSize: '50px'}">{{message}}</h2> 19 <!--finalSize 当作一个变量--> 20 <h2 :style="{fontSize: finalSize + 'px', backgroundColor: finalColor}">{{message}}</h2> 21 <!--调用函数--> 22 <h2 :style="getStyle1()">{{message}}</h2> 23 24 <!--2.v-bind绑定style的数组语法--> 25 <h2 :style="[testStyle1, testStyle2]">{{message}}</h2> 26 <h2 :style="getStyle2()">{{message}}</h2> 27 </div> 28 29 <!--导入Vue.js--> 30 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> 31 <script type="text/javascript"> 32 let vm = new Vue({ 33 el: '#vue', 34 data: { 35 message: "test vue", 36 finalSize: 100, 37 finalColor: "red", 38 testStyle1: {fontSize: "100px"}, 39 testStyle2: {backgroundColor: "red"} 40 41 }, 42 methods: { 43 getStyle1: function () { 44 return { 45 fontSize: this.finalSize + "px", 46 backgroundColor: this.finalColor 47 } 48 }, 49 getStyle2: function () { 50 return [this.testStyle1, this.testStyle2]; 51 } 52 53 } 54 55 56 }); 57 </script> 58 </body> 59 </html>