国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue 實現小程序或商品秒殺倒計時

2024-05-06 15:40:43
字體:
來源:轉載
供稿:網友

下面先給大家介紹下vue 設計一個倒計時秒殺的組件 ,具體內容如下所述:

簡介:

倒計時秒殺組件在電商網站中層出不窮  不過思路萬變不離其蹤,我自己根據其他資料設計了一個vue版的

核心思路:1、時間不能是本地客戶端的時間  必須是服務器的時間這里用一個settimeout代替 以為時間必須統一 

                 2、開始時間,結束時間通過父組件傳入,當服務器時間在這個開始時間和結束時間的范圍內  參加活動按鈕可以點擊,并且參加過活動以后不能再參加,

     3、在組件創建的時候 同步得到現在時間服務時間差,并且在這里邊設置定時器,每秒都做判斷看秒殺是否開始和結束,

     4、在更新時間的函數中是否開始和結束,

     5、在computed鉤子中監聽disable 確定按鈕是否可點擊

     6、參加過活動在updated中停止定時器的計時,頁面銷毀的時候也停止計時

    下邊是代碼

    子組件  

<template> <div>  <button @click="handleClick" :disabled="disabled">   {{btnText}}  </button>  <span>{{tip}}</span> </div></template><script> import moment from 'moment' export default {  name: "Spike",  props: {   startTime: {    required: true,    validator: (val) => {     return moment.isMoment(val)    }   },   endTime: {    required: true,    validator: (val) => {     return moment.isMoment(val)    }   }  },  data() {   return {    start: false,    end: false,    done: false,    tip: '',    timeGap: 0,    btnText:""   }  },   computed: {   disabled() {    //當三個異號的時候disable返回真,不可點擊,    // 初始化通過this.updateState確定disable的狀態    return !(this.start && !this.end && !this.done);   }  },  async created() {   const serverTime=await this.getServerTime();   this.timeGap=Date.now()-serverTime;//當前時間和服務器時間差   this.updateState();   this.timeInterval=setInterval(()=>{    this.updateState()   },1000)  },  updated(){   if(this.end||this.done){    clearInterval(this.timeInterval)   }  },  methods: {   handleClick() {    alert("提交成功");    this.done=true;    this.btnText="已參加過活動"   },   getServerTime() {    //模擬服務器時間    return new Promise((resolve, reject) => {     setTimeout(() => {      //當前時間慢10秒就是服務器時間      resolve(new Date(Date.now() -10 * 1000).getTime())//跟本地時間差     }, 0)    })   },   updateState() {    const now = moment(new Date(Date.now() - this.timeGap));//當前服務器時間    const diffStart=this.startTime.diff(now);//開始時間和服務器時間之差    const diffEnd=this.endTime.diff(now);//結束時間和服務器時間之差    if(diffStart<0){     this.start=true;     this.tip="秒殺已開始";     this.btnText="參加"    }else{     this.tip=`距離秒殺開始還剩${Math.ceil(diffStart/1000)}秒`;     this.btnText="活動未開始";    }    if(diffEnd<=0){     this.end=true;     if( !this.btnText==="已參加過活動"||this.btnText==="參加"){      this.tip="秒殺已結束";      this.btnText="活動已結束";     }    }   }  },  beforeDestroy() {   clearInterval(this.timeInterval)  } }</script><style scoped> button[disabled]{  cursor: not-allowed; }</style>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 晋城| 昆山市| 无棣县| 临江市| 迭部县| 余江县| 涟水县| 桃园县| 杨浦区| 康定县| 沧源| 油尖旺区| 天台县| 扬州市| 伊吾县| 新源县| 仪陇县| 滁州市| 渝中区| 璧山县| 吴江市| 靖西县| 合肥市| 明光市| 黄冈市| 府谷县| 阜阳市| 龙江县| 合肥市| 义乌市| 阿荣旗| 嘉禾县| 岐山县| 高州市| 鹤山市| 青龙| 报价| 东丰县| 镇平县| 上思县| 田东县|