Vue中使用transition标签实现多组件切换动画

257 阅读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>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    const app = Vue.createApp({
      // 变量
      data() {
        return {
          isShow: false,
        };
      },
      //   逻辑
      methods: {
        handleClick() {
          this.isShow = !this.isShow;
        },
      },
      // 模板,里面使用2个组件
      template: `
        <welcome v-if="isShow"/>
        <goodby v-else />
        <button @click="handleClick">切换</button>
        `,
    });
    // 定义全局组件
    app.component("welcome", {
      template: `
        <h1>我是welcome组件</h1>
        `,
    });
    app.component("goodby", {
      template: `
        <h1>我是goodby组件</h1>
        `,
    });
    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>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    const app = Vue.createApp({
      // 变量
      data() {
        return {
          currentComponent: "welcome",
        };
      },
      //   逻辑
      methods: {
        handleClick() {
          if (this.currentComponent === "welcome") {
            this.currentComponent = "goodby";
          } else {
            this.currentComponent = "welcome";
          }
        },
      },
      // 模板,里面使用动态绑定组件<component :is="" />
      template: `
       <transition>
        <component :is="currentComponent" />
        </transition>
        <button @click="handleClick">切换</button>
        `,
    });
    // 定义全局组件
    app.component("welcome", {
      template: `
        <h1>我是welcome组件</h1>
        `,
    });
    app.component("goodby", {
      template: `
        <h1>我是goodby组件</h1>
        `,
    });
    const vm = app.mount("#root");
  </script>
</html>