【VUE】Class 与 Style 绑定

官方链接

Class 与 Style 绑定 — Vue.js
https://cn.vuejs.org/v2/guide/class-and-style.html

笔记例子

效果图

代码

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title></title>
  <script src="vue.js"></script>
  <style>
    .red {
      color: red;
    }

    .fontBig {
      font-size: larger;
    }
  </style>
</head>

<body>
  <div id="vueApp">
    <div :class="{red:isRed}" @click="clickDiv1">
      class绑定对象写法 :class="{类名1:真假,类名2:真假}"
    </div>
    <div :class="[{red:isRed},fontClassName]" @click="clickDiv2">
      class绑定数组写法 :class="[对象,class名变量]"
    </div>
    <div :style="{fontSize:fontSizeName,color:colorName}" @click="clickDiv3">
      style绑定对象写法 :style="JS对象"
    </div>
    <div :style="[baseStyleObj,colorStyleObj]">
      style绑定数组写法 :style="[JS对象1,JS对象2]"
    </div>
  </div>
</body>
<script>
  //初始化VUE页面
  var vm = new Vue({
    el: "#vueApp",
    data: {
      isRed: false,
      fontClassName: "fontBig",
      colorName: "black",
      fontSizeName: "small",
      baseStyleObj: {
        fontSize: "small",
      },
      colorStyleObj: {
        color: "red",
      }
    },
    watch: {
      fontSizeName: function (val) {
        this.baseStyleObj.fontSize = this.fontSizeName;
      },
      colorName: function (val) {
        this.colorStyleObj.color = this.colorName;
      }

    },
    methods: {
      clickDiv1: function () {
        this.isRed = !this.isRed;
      },
      clickDiv2: function () {
        this.isRed = !this.isRed;
      },
      clickDiv3: function () {
        if (this.colorName === "black") {
          this.colorName = "red";
        } else {
          this.colorName = "black";
        }

        if (this.fontSizeName === "small") {
          this.fontSizeName = "larger";
        } else {
          this.fontSizeName = "small";
        }
      }
    }
  });
</script>

</html>
原文地址:https://www.cnblogs.com/chang-an/p/12329185.html