温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue计时器怎么用

发布时间:2021-06-25 15:54:44 来源:亿速云 阅读:157 作者:小新 栏目:开发技术

小编给大家分享一下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. 创建一个要控制的区域 -->
  <div id="app">
    <input type="button" value="加" @click="add">
    <input type="button" value="停" @click="stop">
    <h5>{{ count }}</h5>
  </div>
 
  <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>
    <div class="timer">
    <div ref="startTimer"></div>
    </div>
    </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计时器怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI