您的位置:好站长外链 > 站长新闻 > 软件 >

Vue计时器的用法详解

文章来源:好站长外链

作者:互联网

人气:20

2021-06-27

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

功能简介:

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

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

源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!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">
    <h4>{{ count }}</h4>
  </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>

之前小编收藏了一个开始计时的组件,这个组件可直接引入到项目中使用,谢谢原作者分享。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<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>
 

上一篇:js实现网页音乐播放器

下一篇:没有了

相关文章

在线客服

外链咨询

扫码加我微信

微信:841909564

返回顶部