本文实例为大家分享了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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。
您可能感兴趣的文章:
- 基于Vue方法实现简单计时器
- Vue-cli框架实现计时器应用
- 使用vue实现计时器功能
- vue.js实现简单计时器功能
- vue实现简易计时器组件
- vue计时器的实现方法
- 解决vue组件销毁之后计时器继续执行的问题
- Vue 使用计时器实现跑马灯效果的实例代码
- vue 计时器组件的实现代码
- vue3封装计时器组件的方法
声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。


评论(0)