- 资讯首页 > 开发技术 > web开发 > JavaScript >
- 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"> <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>
之前小编收藏了一个开始计时的组件,这个组件可直接引入到项目中使用,谢谢原作者分享。
<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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
免责声明:本站发布的内容(图片、视频和文字)以原创、来自本网站内容采集于网络互联网转载等其它媒体和分享为主,内容观点不代表本网站立场,如侵犯了原作者的版权,请告知一经查实,将立刻删除涉嫌侵权内容,联系我们QQ:712375056,同时欢迎投稿传递力量。
Copyright © 2009-2022 56dr.com. All Rights Reserved. 特网科技 特网云 版权所有 特网科技 粤ICP备16109289号
域名注册服务机构:阿里云计算有限公司(万网) 域名服务机构:烟台帝思普网络科技有限公司(DNSPod) CDN服务:阿里云计算有限公司 百度云 中国互联网举报中心 增值电信业务经营许可证B2
建议您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流浏览器浏览本网站