网络编程
位置:首页>> 网络编程>> JavaScript>> uni-app使用countdown插件实现倒计时

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

作者:Laladoge  发布时间:2024-05-10 14:15:14 

标签:uni,app,倒计时

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

实现的效果如下:

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

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

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

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

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


<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>

来源:https://blog.csdn.net/Laladoge/article/details/106761926

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com