vue 计时器组件的实现代码
程序员文章站
2022-09-08 12:56:19
整理文档,搜刮出一个vue 计时器组件的代码,稍微整理精简一下做下分享。
整理文档,搜刮出一个vue 计时器组件的代码,稍微整理精简一下做下分享。
<template> <div> <span :sendsync="sendsync" :autostart="autostart" :defaultval="defaultval" >{{countstring}}</span> </div> </template> <script> export default { data() { return { isstart: false, globaltimer: null,//获取setinterval对象值 countstring: '0秒', //用来显示时间 day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, countval: this.defaultval, //获取初始值 pausetime: 0, } }, watch: { 'countstring': { deep: true, handler: function(val, oldval) { var vm = this if (vm.needsendsunc) { vm.passtoparent(val) } } }, 'needsendsunc': { deep: true, handler: function(val) { var vm = this if (val) { vm.passtoparent(vm.countstring) } } } }, props: { sendsync: { type: boolean, default: false, }, autostart: { type: boolean, default: false, }, defaultval: { type: number, default: 0, } }, mounted() { var vm = this if (vm.autostart) { vm.startcountfn() } }, computed: { needsendsunc: function() { return this.sendsync } }, created: function() { this.$on('startcount', function() { this.startcountfn() }); this.$on('stopcount', function() { this.stopcountfn() }); }, components: {}, methods: { counterfn: function(countertime) { var vm = this var nowdate = new date().gettime() if(vm.pausetime == 0){ var num = nowdate - countertime //计算时间毫秒差 }else{ vm.pausetime = vm.pausetime +10 var num = vm.pausetime - countertime //计算时间毫秒差 } var leave1 = num % (24 * 3600 * 1000) //计算天数后剩余的毫秒数 var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数 var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数 vm.day = math.floor(num / (24 * 3600 * 1000)) //计算相差天数 vm.hour = math.floor(leave1 / (3600 * 1000))//计算相差小时 vm.minute = math.floor(leave2 / (60 * 1000))//计算相差分钟 vm.second = math.round(leave3 / 1000) //计算相差秒 if (vm.day > 0) { vm.countstring = `${vm.day}天 ${vm.hour}小时 ${vm.minute}分 ${vm.second}秒`; } else if (vm.hour > 0) { vm.countstring = `${vm.hour}小时 ${vm.minute}分 ${vm.second}秒`; } else if (vm.minute > 0) { vm.countstring = `${vm.minute}分 ${vm.second}秒`; } else { vm.countstring = `${vm.second}秒`; } }, startcountfn: function() { var vm = this if (!vm.isstart) { vm.countval = vm.countval ? vm.countval : new date().gettime() var timer = setinterval(function() { vm.counterfn(vm.countval) }, 10) vm.globaltimer = timer vm.isstart = true } }, stopcountfn: function() { var vm = this if (vm.isstart) { window.clearinterval(vm.globaltimer) vm.globaltimer = null; vm.isstart = false vm.pausetime = new date().gettime() } }, passtoparent: function(data) { var vm = this this.$emit("getdatafromchild", data) }, } } </script> <style> </style>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 微信小程序之页面拦截器的示例代码