vue實現(xiàn)秒殺倒計時組件
本文實例為大家分享了vue實現(xiàn)秒殺倒計時組件的具體代碼,供大家參考,具體內容如下
下面是使用Vue實現(xiàn)秒殺倒計時組件
開發(fā)思路
1.請求服務器獲取這一刻的服務器時間(統(tǒng)一以服務器時間為基準)
2.獲取用戶當前電腦時間與服務器時間比對,獲取時間差。以當前電腦時間-減去時間差為最終時間(定義為服務器當前時間)
3.設置秒殺開始時間
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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
django使用channels2.x實現(xiàn)實時通訊
這篇文章主要介紹了django使用channels2.x實現(xiàn)實時通訊,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11最全vue的vue-amap使用高德地圖插件畫多邊形范圍的示例代碼
這篇文章主要介紹了最全vue的vue-amap使用高德地圖插件畫多邊形范圍,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07詳解如何配置vue-cli3.0的vue.config.js
這篇文章主要介紹了詳解如何配置vue-cli3.0的vue.config.js,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08