在vue中添加實時時間


    一:在data中定義一個字符串,用於保存時間:nowTime

    二:在methods鈎子函數中定義三個函數(注意:"星期"+'日一二三四五六'.charAt(new Date().getDay())   這段代碼用來獲取具體的星期幾) 

timeFormate(timeStamp) {
  let year = new Date(timeStamp).getFullYear();
  let month =new Date(timeStamp).getMonth() + 1 < 10? "0" + (new Date(timeStamp).getMonth() + 1): new Date(timeStamp).getMonth() + 1;
  let date =new Date(timeStamp).getDate() < 10? "0" + new Date(timeStamp).getDate(): new Date(timeStamp).getDate();
  let hh =new Date(timeStamp).getHours() < 10? "0" + new Date(timeStamp).getHours(): new Date(timeStamp).getHours();
  let mm =new Date(timeStamp).getMinutes() < 10? "0" + new Date(timeStamp).getMinutes(): new Date(timeStamp).getMinutes();
  let ss =new Date(timeStamp).getSeconds() < 10? "0" + new Date(timeStamp).getSeconds(): new Date(timeStamp).getSeconds();
  this.nowTime = year + "." + month + "." + date +"  "+"星期"+'日一二三四五六'.charAt(new Date().getDay())+" "+hh+":"+mm+':'+ss ;
},
nowTimes(){
  this.timeFormate(new Date());
  setInterval(this.nowTimes,1000);
  this.clear()
},
clear(){
  clearInterval(this.nowTimes)
  this.nowTimes = null;
}

 

    三:在mounted鈎子函數中調用nowTimes函數、在beforeDestroy鈎子函數中調用clear函數

mounted() {
      this.nowTimes();
    },
    beforeDestroy() {
      this.clear();
    }

 

    四:最后,顯示在界面上

<div class="head_date">{{nowTime}}</div>

 

 

 

借鑒地址:https://blog.csdn.net/qq_42647749/article/details/100741957

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM