vue實現(xiàn)秒殺倒計時組件
本文實例為大家分享了vue實現(xiàn)秒殺倒計時組件的具體代碼,供大家參考,具體內(nèi)容如下
下面是使用Vue實現(xiàn)秒殺倒計時組件

開發(fā)思路
1.請求服務器獲取這一刻的服務器時間(統(tǒng)一以服務器時間為基準)
2.獲取用戶當前電腦時間與服務器時間比對,獲取時間差。以當前電腦時間-減去時間差為最終時間(定義為服務器當前時間)
3.設(shè)置秒殺開始時間
4.秒殺時間與服務器當前時間比對,獲取時間差(共X秒)
5.根據(jù)X秒計算出離秒殺開始時間還有x天x小時x分鐘x秒
代碼實現(xiàn)
下面代碼只展示第4、第5步驟
組件CountDown.vue
<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>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- 解決vue項目本地啟動時無法攜帶cookie的問題
- vue項目啟動出現(xiàn)cannot GET /服務錯誤的解決方法
- Vue修改項目啟動端口號方法
- 詳解webpack打包vue項目之后生成的dist文件該怎么啟動運行
- 詳解VSCode配置啟動Vue項目
- webpack+vue+express(hot)熱啟動調(diào)試簡單配置方法
- vue-cli啟動本地服務局域網(wǎng)不能訪問的原因分析
- 詳解vue express啟動數(shù)據(jù)服務
- vue實現(xiàn)商品詳情頁功能之商品選項卡
- Vue2.0/3.0雙向數(shù)據(jù)綁定的實現(xiàn)原理詳解
- 如何啟動一個Vue.js項目
相關(guān)文章
vue axios調(diào)用接口方法報錯500 internal server err
前端使用axios 訪問后端接口時報錯,在瀏覽器中點擊紅色的報錯數(shù)據(jù),本文給大家分享vue axios調(diào)用接口方法報錯500 internal server error的兩種解決方法,感興趣的朋友一起看看吧2023-10-10

