使用vue实现动画效果

54 阅读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>
      /* 定义一个动画,从左往右 */
      /* 定义关键帧 */
      @keyframes left2right {
        0% {
          transform: translate(0px);
        }
        25% {
          transform: translate(-100px);
        }
        50% {
          transform: translate(0px);
        }
        75% {
          transform: translate(100px);
        }
        100% {
          transform: translate(0px);
        }
      }
      /* 定义一个animation */
      /* 只要调用了这个类,就会有动画效果 */
      .animation {
        animation: left2right 3s;
      }
    </style>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    const app = Vue.createApp({
      // 变量
      data() {
        return {
          hello: "hello world",
          animate: {
            animation: false,
          },
        };
      },
      //   如果变量不写在data里面,就是自定义属性
      //   用的时候需要用$options来打点调用
      world: "我是自定义的属性",
      //   逻辑
      methods: {
        handleClick() {
          this.animate.animation = !this.animate.animation;
        },
      },
      // 模板,动态绑定一个类,v-bind:class="animate"
      //   模板里面添加自定义属性,要用$options打点调用
      template: `
<h1 v-bind:class="animate"  >{{hello}}</h1>
<div>{{$options.world}}</div>
<button v-on:click="handleClick" >点击切换</button>
`,
    });
    const vm = app.mount("#root");
  </script>
</html>