因为class的绑定在实际的工作中会经常用到。所以特意记录一下,有好几种方法。
对象绑定方法,另外一个值来控制显示隐藏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> <style> .active{ color: red; } </style> </head> <body> <div id="vue_det"> <!--active是上面定义好的类名,flag是你设置的布尔变量--> <h1 :class="{active:flag}" @click="details">site : {{site}}</h1> </div> <script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { site: "菜鸟教程", flag:false }, methods: { details: function() { this.flag=!this.flag; //点击来控制字体颜色切换 } } }) </script> </body> </html>
数组的方法,数组里面的变量就是class的类名(同理数组里面可以放多个类名)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> <style> .active{ color: red; } </style> </head> <body> <div id="vue_det"> <!--active是上面定义好的类名--> <h1 :class="[active]" @click="details">site : {{site}}</h1> </div> <script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { site: "菜鸟教程", active:'' }, methods: { details: function() { this.active=this.active==="active"?"":"active"; //点击来控制字体颜色切换 } } }) </script> </body> </html>
style绑定对象的方式,后面绑定的对象的值就是style的样式属性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> <style> .active{ color: red; font-size: 30px; } </style> </head> <body> <div id="vue_det"> <!--active是上面定义好的类名--> <sapn :style="obj" @click="details">site : {{site}}</sapn> </div> <script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { site: "菜鸟教程", obj:{ color:'red', fontSize : '30px' } }, methods: { details: function() { this.obj.color='green'; //点击来控制字体颜色切换 } } }) </script> </body> </html>
style绑定数组的方式,后面的数组的值可以有多个
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> </head> <body> <div id="vue_det"> <!--active是上面定义好的类名--> <sapn :style="[obj,obj2]" @click="details">site : {{site}}</sapn> </div> <script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { site: "菜鸟教程", obj:{ color:'red' }, obj2:{ fontSize : '30px' } }, methods: { details: function() { this.obj.color='green'; //点击来控制字体颜色切换 } } }) </script> </body> </html>