Vue学习小札——2.2 样式绑定

198 阅读1分钟

class的对象绑定

<style>.activated { color:red; }</style>
</head>
<body>
  <div id="app">
     <div @click="handleDivClick"
          :class="{activated: isActivated}">
          hello world
     </div>
  </div>
  
  <script>
   var vm = new Vue({
     el:"#app",
     data: {
      isActivated: false,
     },
     methods: {
      handleDivClick: function() {
        this.isActivated = !this.isActivated;
      }
     }    
   });
  </script>
</body>


class的数组绑定

<style>.activated { color:red; }</style>
</head>
<bidy>
 <div id="app"> 
     <div @click="handleDivClick"
          :class="[activated,activatedOne]">
          hello world
     </div>
  </div>
  
  <script>
   var vm = new Vue({
     el:"#app",
     data: {
      activated:"",
      activatedOne:"activated-one",
     },
     methods: {
      handleDivClick: function() {
       //  if(this.activated ==="activated"){
       //    this.activated = "";
       //  } else {
       //  this.activated = "activated";
       // }  
        this.activated = this.activated ==="activated" ? "" : "activated";
      }
     }    
   });
  </script>
</body>


内联样式的对象绑定

<div id="app">
     <div :style="styleObj" 
          @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>


内联样式的数组绑定

 <div id="app">
     <div :style="[styleObj,styleObjOne,{lineHeight:'50px'}]" 
          @click="handleDivClick">
          hello world
     </div>
  </div>
  
  <script>
   var vm = new Vue({
     el:"#app",
     data: {
      styleObj:{
        color:"black"
      },
      styleObjOne:{
        fontSize:"30px"
      }
     },
     methods: {
      handleDivClick: function() {
        this.styleObj.color = this.styleObj.color === "black" ? "red" : "black";
      }
     }    
   });
  </script>