1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>动态绑定类名</title> 6 <link rel="stylesheet" type="text/css" href="vue.css"> 7 <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> 8 </head> 9 <body> 10 <div id="vue-app"> 11 <h1>动态 CSS CLASS </h1> 12 13 <h2> 示例 1</h2> 14 <div v-bind:class="{changeColor:changeColor}"> 15 <span>你妹的</span> 16 </div> 17 <!--这里绑定单击事件 相当于 给自己取反---> 18 <div v-on:click="changeColor=!changeColor" v-bind:class="{changeColor:changeColor}"> 19 <span>你妹的</span> 20 </div> 21 22 <h2 v-bind:class="{red:false}">示例 2 false 静态更改 样式</h2> 23 <h2 v-bind:class="{red:true}">示例 2 true,查看样式注意有什么不同之处</h2> 24 25 26 <button v-on:click="changeColor=!changeColor"> change color</button> 27 <button v-on:click="changeLength=!changeLength"> change length</button> 28 <div v-bind:class="compClasses"> 29 <span>大哥哥</span> 30 </div> 31 </div> 32 33 34 <script src="app.js"></script> 35 </body> 36 </html>
1 new Vue({ 2 el:'#vue-app', 3 data:{ 4 changeColor:false, 5 changeLength:false 6 }, 7 methods:{ 8 9 }, 10 computed:{ 11 compClasses:function(){ 12 return { 13 changeColor:this.changeColor, 14 changeLength:this.changeLength 15 } 16 } 17 } 18 19 })
1 span{ 2 background:red; 3 display:inline-block; 4 padding:10px; 5 color:#fff; 6 margin: 10px 0; 7 } 8 9 .changeColor span{ 10 background:green; 11 } 12 13 .changeLength span:after{ 14 content:"length"; 15 margin-left:10px; 16 }