vue中实现过渡的不同方式

21 阅读1分钟
<!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>
    <script src="https://unpkg.com/vue@next"></script>
    <!-- 定义样式 -->
    <style>
      .transition {
        /* transition: 过渡属性 过渡时长 运动速度 延迟时间; */
        transition: 1s background linear;
      }
      .orangered {
        background-color: orangered;
      }
      .green {
        background-color: green;
      }
    </style>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    const app = Vue.createApp({
      // 变量,把类名做成变量,在标签里面动态绑定
      data() {
        return {
          myData: {
            transition: true,
            orangered: true,
            green: false,
          },
        };
      },
      //   逻辑
      methods: {
        // 点击的时候类取反
        handleClick() {
          this.myData.orangered = !this.myData.orangered;
          this.myData.green = !this.myData.green;
        },
      },
      // 模板
      template: `
      <h1 v-bind:class="myData">hello world</h1>
        <button @click="handleClick">切换</button>
        `,
    });
    const vm = app.mount("#root");
  </script>
</html>

另一种方式

<!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>
    <script src="https://unpkg.com/vue@next"></script>
    <style>
      .transition {
        transition: 1s background linear;
      }
    </style>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    const app = Vue.createApp({
      // 变量
      data() {
        return {
          styleObj: {
            backgroundColor: "red",
          },
        };
      },
      //   逻辑
      methods: {
        handleClick() {
          if (this.styleObj.backgroundColor === "red") {
            this.styleObj.backgroundColor = "green";
          } else {
            this.styleObj.backgroundColor= "red";
          }
        },
      },
      // 模板
      template: `
      <h1 class="transition" :style="styleObj">hello world</h1>
<button @click="handleClick">点击</button>
`,
    });
    const vm = app.mount("#root");
  </script>
</html>