vue2 - 绑定class,绑定style

1.绑定class样式

字符串写法:适用于类名不确定,要动态获取

数组写法适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用。

对象写法适用于:要绑定多个样式,个数不确定,名字也不确定

<div id="root">
    <!--类为class1-->
    <div v-bind:class="classStr"></div>
    <!--类为class1 class2 class3-->
    <div v-bind:class="arrayClass"></div>
    <!--类为class1 因为class1为true-->
    <div v-bind:class="objClass"></div>
  </div>

  <script>
    const vm=new Vue({
      el: "#root",
      data: {
        //字符串写法
        classStr: "class1",
        //数组写法
        arrayClass: ["class1","class2","class3"],
        //对象写法 为true时代表启用,为false时代表停用
        objClass: {
          class1: true,
          class2: false
        }
      }
    });
  </script>

 

2.绑定style

<div id="root">
    <!--对象写法-->
    <div v-bind:style="ObjStyle"></div>
    <!--数组写法-->
    <div v-bind:style="arrayStyle"></div>
  </div>

  <script>
    const vm=new Vue({
      el: "#root",
      data: {
        //对象写法
        ObjStyle: {
          backgroundColor: "pink",
          fontSize: "22px",
          color: "red"
        },
        //数组写法
        arrayStyle: [
          {
            backgroundColor: "pink",
            color: "red"
          },
          {
            fontSize: "22px"
          }
        ]
      }
    });
  </script>

 

posted on 2023-02-16 22:02  Mikasa-Ackerman  阅读(97)  评论(0编辑  收藏  举报

导航