vue實現同時設置多個倒計時
本文實例為大傢分享瞭vue實現同時設置多個倒計時的具體代碼,供大傢參考,具體內容如下
html如下:
<div class="home"> <tbody> <tr v-for="(item, index) in bargainGoods" :key="index"> <td v-text="item.down + Djs_timeList(item.countDown)"></td> </tr> </tbody> </div>
js如下:
export default { data() { return { bargainGoods: [], total: 0, page: 1, serverTime: 0, timer: "" // hostUrl: this.$hostUrl }; }, //用於數據初始化 created: function() { // 獲取數據 this.goods(); // 獲取服務器時間 this.findServiceTime(); }, methods: { goods: function() { var _this = this; _this.$axios({ url: "goods/pageGoods", data: { current: -1, activityStatus: "", limit: -1, status: "SALE" }, success: response => { _this.bargainGoods = response.items; _this.Djs_time();// 調用定時器 // 以下是我處理的後臺返回數據 開始時間和結束時間,頁面顯示用的 if (_this.bargainGoods.length != 0) { for (var key in _this.bargainGoods) { var hour = 0; var startime = 0; if (_this.bargainGoods[key] != null) { _this.bargainGoods[key].countDown = ""; _this.bargainGoods[key].down = ""; // 結束時間 hour = _this.bargainGoods[key].overTime; startime = _this.bargainGoods[key].activityStartTime; hour = hour.replace(/-/g, "/"); hour = new Date(hour).getTime(); startime = startime.replace(/-/g, "/"); startime = new Date(startime).getTime(); // 如果結束時間大於當前時間 if (hour > _this.serverTime && startime < _this.serverTime) { var hourtime = hour - _this.serverTime; if (hourtime > 0) { _this.bargainGoods[key].down = "結束倒計時:"; _this.bargainGoods[key].countDown = _this.bargainGoods[key].overTime; } } else if (startime > _this.serverTime) { var starhourtime = startime - _this.serverTime; if (starhourtime > 0) { _this.bargainGoods[key].down = "開始倒計時:"; _this.bargainGoods[key].countDown = _this.bargainGoods[key].activityStartTime; } } else { _this.bargainGoods[key].down = "已結束"; _this.bargainGoods[key].countDown = ""; } // console.log(_this.bargainGoods); } } _this.bargainGoods = _this.bargainGoods; } } }); }, // 獲取服務器時間 findServiceTime() { var _this = this; _this.$axios({ url: "serverTime/getDateTime", success: function(res) { _this.serverTime = res.item; } }); }, Djs_time: function() { this.timer = setInterval(() => { this.serverTime = this.serverTime + 1000; }, 1000); }, Djs_timeList: function(itemEnd) { // 此處 itemEnd 的日期是年月日時分秒 var endItem = new Date(itemEnd).getTime(); //獲取列表傳的截止時間,轉成時間戳 var nowItem = this.serverTime; //獲取當前時間 var rightTime = endItem - nowItem; //截止時間減去當前時間 if (rightTime > 0) { //判斷剩餘倒計時時間如果大於0就執行倒計時否則就結束 var dd = Math.floor(rightTime / 1000 / 60 / 60 / 24); var hh = Math.floor((rightTime / 1000 / 60 / 60) % 24); var mm = Math.floor((rightTime / 1000 / 60) % 60); var ss = Math.floor((rightTime / 1000) % 60); var showTime = dd + "天" + hh + "小時" + mm + "分" + ss + "秒"; } else { var showTime = ""; } return showTime; }, }, //離開頁面後清除定時器 destroyed() { clearInterval(this.timer); } };
效果如下:
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- JavaScript實現限時秒殺功能
- vue實現時間倒計時功能
- 微信小程序基於數據庫時間實現商品倒計時功能(可重用代碼)
- 微信小程序實現倒計時
- 微信小程序拍賣商品詳情頁設計與交互實現代碼(含倒計時、實時更新出價)