富贵资源网 Design By www.hznty.com

整理文档,搜刮出一个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 "getDataFromChild", data)
  },
 }
}
</script>
<style>

</style>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com