1. 程式人生 > >vue動態繫結class的3種方式物件語法和陣列語法

vue動態繫結class的3種方式物件語法和陣列語法

動態繫結class的幾種方式

1.物件語法 行內或計算屬性

<style>
    .static {
      width: 100px;
      height: 100px;
      background-color: #ccc;
    }
    .orange {
      border: 1px solid orange;
    }
  </style>
</head>
<body>
  <!-- 物件語法 -->
  <!-- <div id="example" class="static" v-bind:class="{'orange': isRipe, 'green': isNotRipe}"></div> -->
  <div id="example" class="static" v-bind:class="haha"></div>
</body>
  // 01class繫結方法1物件語法
  var vm = new Vue({
    el: "#example",
    data: {
      //   isRipe: true,
      //   isNotRipe: false
      age: 4,
      member: 999
    },
    computed: {
      haha: function() {
        return {
          'orange': this.age > 3 ? true : false,
          'green': this.member > 1000 ? true : false
        }
      }
    }
  })

方法2陣列語法

 // 陣列語法 
  <div id="example" class="static" v-bind:class="[class1, class2]"></div>
  var vm = new Vue({
    el: "#example",
    data: {
      class1: 'orange',
      class2: 'green'
    }
  })

方法3繫結行內樣式

  <!-- 物件語法 -->
  // <div id="app" v-bind:style="{color: color, fontSize: fontSize+'px' }">hello world</div> -->
 // <div id="app" v-bind:style="style">hello world</div>
  <div id="app" v-bind:style="haha">hello world</div>
    var vm = new Vue({
      el: '#app',
      data: {
        // color: 'pink',
        // fontSize: 30
        // style: {
        //   color: 'pink',
        //   fontSize: '30px'
        // }
        age: 4,
        member: 9000
      },
      computed: {
        haha : function() {
          return {
            color: this.age >3 ? orange: green,
            fontSize: this.member> 1000 ? '30px' :'10px'
          }
        }
      }
    })