uni-app使用countdown插件实现倒计时

本文实例为大家分享了使用countdown插件实现倒计时的具体代码,供大家参考,具体内容如下

实现的效果如下:

这里实现的是一个活动倒计时,获取当前时间和活动开始时间,相减得出的时间差就是我们需要的倒计时。使用插件很方便。

首先新建一个项目,选择uni-app,模板选择hello-uniapp,里面有官网的组件可以直接使用。创建之后将components整个文件夹复制到自己的项目中。

在需要使用倒计时的页面引入组件

<script>
 import unicountdown from '@/components/uni-countdown/uni-countdown.vue'
 export default {
 data() {
  return {
  d:'',
  h:'',
  m:'',
  n:''
  }
 },
 
 components:{
  unicountdown
 }
 }
</script>

在页面中放置定时器的位置

<view class="created" v-if="mydata.stat == '未拍卖'">
 <span>距开始剩</span>
 <span class="timer">
    <uni-countdown :day="d" :hour="h" :minute="m" :second="s"></uni-countdown>
  </span>
</view>

计算定时器中绑定的时间d,h,m,s

var date = new date();
  var now = date.gettime();
  var star = this.mydata.starttime
  var enddate = new date(star); 
  var end = enddate.gettime(); 
  var lefttime = end-now;
  if (lefttime >= 0) {
 this.d = math.floor(lefttime/1000/60/60/24); 
 this.h = this.mydata.validtime+math.floor(lefttime/1000/60/60%24); 
 this.m = math.floor(lefttime/1000/60%60); 
 this.s = math.floor(lefttime/1000%60);
 console.log(this.d+'天'+this.h+'时'+this.m+'分'+this.s+'秒')
}

完整代码:

<template>
  <view class="created">
 <span>距开始剩</span>
 <span class="timer">
      <uni-countdown :day="d" :hour="h" :minute="m" :second="s"></uni-countdown>        
    </span>
 </view>
</template>
<script>
 import unicountdown from '@/components/uni-countdown/uni-countdown.vue'
 export default {
 data() {
  return {
  d:'',
  h:'',
  m:'',
  n:'',
  }
 },
 onload(option){
  this.init()
 },
 
 methods: {
  init(){
        var date = new date();
  var now = date.gettime();//获得当前时间与1970年1月1日时间相差的毫秒数
  var star = this.mydata.starttime
  var enddate = new date(star); 
  var end = enddate.gettime();//结束时间与1970年1月1日时间相差的毫秒数
  var lefttime = end-now;//计算两日期之间相差的毫秒数
  if (lefttime >= 0) {
   this.d = math.floor(lefttime/1000/60/60/24);
   this.h = math.floor(lefttime/1000/60/60%24); 
   this.m = math.floor(lefttime/1000/60%60); 
   this.s = math.floor(lefttime/1000%60);
   console.log(this.d+'天'+this.h+'时'+this.m+'分'+this.s+'秒')
  }
      }
    },
 components:{
  unicountdown
 }
 }
</script>

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

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐