【Vue3 从入门到实战 进阶式掌握完整知识体系】023-Vue中的动画:状态动画

220 阅读1分钟

5、状态动画

代码

<!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>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>
  const app = Vue.createApp({
    data(){
      return{
        num: 1
      }
    },
    methods:{
      add(){
        // 变成 10,我希望动画是从 1 2 3 ... 10
        if(this.num < 10){
          const animation = setInterval(() => {
            this.num ++;
            if(this.num === 10){
              clearInterval(animation);
            }
          }, 100);
        }
      }
    },
    template: `
        <div>
          <div>{{num}}</div>
          <button @click="add">增加</button>
        </div>
    `
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210614004639261.png