您的位置:首页 > 编程学习 > > 正文

vue怎么实现倒计时(Vue计时器的用法详解)

更多 时间:2021-10-27 10:31:51 类别:编程学习 浏览量:1965

vue怎么实现倒计时

Vue计时器的用法详解

本文实例为大家分享了Vue实现计时器的具体代码,供大家参考,具体内容如下

vue怎么实现倒计时(Vue计时器的用法详解)

功能简介:

1、初始值为0,点击【加】按钮,数字自+1;连续点击【加】,不影响数字+1

2、点击【停】按钮,停止+1

源码:

  • <!DOCTYPE html>
    <html add="en">
     
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <!-- 1. 导入Vue包 -->
      <script src="./lib/vue-2.4.0.js"></script>
    </head>
     
    <body>
      <!-- 2. 创建一个要控制的区域 -->
      <li id="app">
        <input type="button" value="加" @click="add">
        <input type="button" value="停" @click="stop">
        <h4>{{ count }}</h4>
      </li>
     
      <script>
        var vm = new Vue({
          el: '#app',
          data: {
            count: 0,
            intervalId: null
          },
          methods: {
            add() {
              // 计时器正在进行中,退出函数
              if (this.intervalId != null) { 
                return 
              };
              // 计时器为空,操作
              this.intervalId = setInterval(() => {
                this.count += 1
              }, 400)
            },
            // 停止定时器
            stop() { 
              clearInterval(this.intervalId)//清除计时器
              this.intervalId = null;//设置为null 
            }
          }
        })
      </script>
    </body>
     
    </html>
    
  • 之前小编收藏了一个开始计时的组件,这个组件可直接引入到项目中使用,谢谢原作者分享。

  •  <template>
        <li class="timer">
        <li ref="startTimer"></li>
        </li>
        </template>
        <script>
        export default {
        name: 'Timer',
        data () {
        return {
        timer: "",
        content: "",
        hour: 0,
        minutes: 0,
        seconds: 0
        }
        },
        created () {
        this.timer = setInterval(this.startTimer, 1000);
        },
        destroyed () {
        clearInterval(this.timer);
        },
        
        methods: {
        startTimer () {
        this.seconds += 1;
        if (this.seconds >= 60) {
        this.seconds = 0;
        this.minute = this.minute + 1;
        }
        
        if (this.minute >= 60) {
        this.minute = 0;
        this.hour = this.hour + 1;
        }
        this.$refs.startTimer.innerHTML = (this.minutes < 10 ? '0' + this.minutes : this.minutes) + ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds);
        }
        }
        }
        </script>
        <style>
    </style>
    
  • 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持开心学习网。

    标签:vue 计时器
    您可能感兴趣