本文實例為大家分享了vue實現秒殺倒計時組件的具體代碼,供大家參考,具體內容如下
下面是使用Vue實現秒殺倒計時組件
開發思路
1.請求服務器獲取這一刻的服務器時間(統一以服務器時間為基準)
2.獲取用戶當前電腦時間與服務器時間比對,獲取時間差。以當前電腦時間-減去時間差為最終時間(定義為服務器當前時間)
3.設置秒殺開始時間
4.秒殺時間與服務器當前時間比對,獲取時間差(共X秒)
5.根據X秒計算出離秒殺開始時間還有x天x小時x分鐘x秒
代碼實現
下面代碼只展示第4、第5步驟
組件CountDown.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
< template > < div > < input type = "datetime-local" :min = "currentTime" placeholder = "請輸入秒殺開始時間" v-model = "startTime" > < button @ click = "submit" >開始計時</ button > </ div > < div > < h1 >{{ countDownTime }}</ h1 > </ div > </ template > < script > let timer = null; let tipTextPrefix = '離秒殺開始還有: '; import moment from "moment"; export default { name: 'CountDown', data() { return { currentTime: moment().format('YYYY-MM-DDTHH:mm'), // 請使用步驟1-3計算出來的服務器時間 startTime: moment().format('YYYY-MM-DDTHH:mm'), countDownTime: tipTextPrefix + '0天 0小時 0分鐘 0秒' }}, methods: { submit: function() { const _this = this; clearInterval(timer); timer = setInterval(() => { _this.countDownTime = _this.countDown(); }, 1000); }, countDown: function() { console.log(this.startTime); const seconds = moment(this.startTime).diff(new Date, 'seconds'); if (seconds <= 0) { clearInterval(timer); return '秒殺已開始'; } const second = seconds%60; const minutes = (seconds-second) / 60; const minute = minutes%60; const hours = (minutes-minute) / 60; const hour = hours%24; const day = (hours-hour) / 24; const res = tipTextPrefix + day + '天 '+ hour + '小時 '+ minute + '分鐘 '+ second + '秒 '; return res; } }, } </ script > < style > </ style > |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/aa390481978/article/details/108490229