其他分享
首页 > 其他分享> > 样式绑定的两种方法

样式绑定的两种方法

作者:互联网

通过class绑定

:class="{ activated:isActivated}",根据isActivated的true或false决定dom是否有class="activated"属性

<head>
  <script src="../vue.js"></script>
  <style>
    .activated{
      color: white;
      background-color: tan;
    }
  </style>
</head>
<body>
  <div id="app">
    <div @click="handleDivClick" :class="{activated: isActivated}">
      样式绑定
    </div>
  </div>
  <script>
    var vm = new Vue({
      el: '#app',
      data: {
        isActivated: false
      },
      methods: {
        handleDivClick(){
          this.isActivated = !this.isActivated
        }
      }
    })
  </script>
</body>

class="[activated]",vue实例的data中activated的值即为class的值,数组内表示变量,数组内可填写多个变量

<head>
  <script src="../vue.js"></script>
  <style>
    .activated{
      color: white;
      background-color: tan;
    }
  </style>
</head>

<body>
  <div id="app">
    <div @click="handleDivClick" :class="[activated]">
      样式绑定
    </div>
  </div>
  <script>
    var vm = new Vue({
      el: '#app',
      data: {
        activated: ''
      },
      methods: {
        handleDivClick(){
          this.activated = this.activated === "activated" ? "" : "activated"
        }
      }
    })
  </script>
</body>

通过style进行动态绑定

style的对象绑定::style='styleObj' 实例data中定义styleObj:{color:'red'}

<body>
  <div id="app">
    <div @click="handleDivClick" :style="styleObj">
      样式绑定
    </div>
  </div>
  <script>
    var vm = new Vue({
      el: '#app',
      data: {
        styleObj: {
          color:"black"
        }
      },
      methods: {
        handleDivClick(){
          this.styleObj.color = this.styleObj.color === "black" ? "red" : "black"
        }
      }
    })
  </script>
</body>

 

标签:两种,styleObj,isActivated,样式,绑定,activated,color,data
来源: https://www.cnblogs.com/manhuai/p/14616764.html