<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vue中的样式绑定</title> <script src="./vue.js"></script> <style> .activated { color: red; } .activated-one{ font-size: 78px; } </style> </head> <body> <div id="app"> <div @click='handleDivClick' :class="[activated,activatedOne]"> <!--:class = "{activated:isActivated}"--> <!--class对象绑定--> hello world </div> </div> <script> var vm = new Vue({ el: "#app", data: { // isActivated:false activated: '', activatedOne:'' }, methods: { handleDivClick: function () { // this.isActivated = !this.isActivated //取反 // if (this.activated === "activated") { // this.activated = ''; // } else { // // this.activated = "activated"; //代码过于冗余 // } this.activated = this.activated === "activated" ? "" : "activated" //三元表达式 this.activatedOne = this.activatedOne === "activated-one" ? "" : "activated-one" //三元表达式 } } }) </script> </body> </html> <!-- 两种方法:一个对对象进行绑定,一个是对数组进行绑定 -->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue中内联样式绑定</title> <script src="./vue.js"></script> </head> <body> <div id="app"> <!--<div :style="styleObj" @click="handleDivClick">--> <div :style="[styleObj,{fontSize:'20px'}]" @click="handleDivClick"> hello world </div> </div> <script> var vm = new Vue({ el:"#app", data:{ styleObj:{ color:"black" } }, methods:{ handleDivClick:function () { this.styleObj.color = this.styleObj.color === 'black' ? "red" : "black"; } } }) </script> </body> </html> <!-- 两种方法:一个对对象进行绑定,一个是对数组进行绑定 -->