uni-app使用countdown外掛實現倒計時
阿新 • • 發佈:2020-11-02
本文例項為大家分享了使用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:'',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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。