Vue 动态绑定Class

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  .base {
    background-color: lightpink;
    width: 100px;
    height: 100px;
  }

  .aTest {
    background-color: skyblue;
    width: 100px;
    height: 100px;
  }

  .bTest {
    background-color: orange;
    width: 100px;
    height: 100px;
  }

  .cTest {
    border-radius: 10px;
  }
</style>

<body>
  <div id="root">
    <div class="base" :class="targetStyle" @click="changeStyle">
      {{name}}
    </div>
    <br><br>
    <!-- 绑定class数组写法 -->
    <div :class="arr"></div>
    <br><br>
    <!-- 绑定class对象写法 -->
    <div :class="classObj"></div>
    <br><br>
    <!-- 绑定style对象写法 -->
    <div :style="styleObj" :class="classObj">{{name}}</div>

    <div :style="testClass">哈哈哈哈哈</div>

    <div :class="testObj">class对象绑定</div>
  </div>
</body>
<script src="../VueJs//vue.js"></script>

<script>
  Vue.config.productionTip = false
  var vm = new Vue({
    el: "#root",
    data: {
      name: "哈哈哈哈",
      targetStyle: "",
      arr: ['aTest', 'bTest', 'cTest'],
      classObj: {
        "bTest": true,
        "cTest": true
      },
      styleObj: {
        'font-size': '12px'
      },
      testClass: {
        "background-color": 'red'
      },
      testObj: {
        bTest: true,
        cTest: true
      }
    },
    methods: {
      changeStyle() {
        const arry = ['aTest', 'bTest']
        this.targetStyle = arry[Math.floor(Math.random() * 2)]
      }
    },
  })
</script>

</html>

 

posted @ 2022-04-26 21:10  含泪拒绝王阿姨i  阅读(95)  评论(0)    收藏  举报