1. 程式人生 > 程式設計 >Vue 中獲取當前時間並實時重新整理的實現程式碼

Vue 中獲取當前時間並實時重新整理的實現程式碼

1. 實現程式碼

<template>
 <div>
  {{nowDate}}{{nowWeek}}{{nowTime}}
 </div>
</template>

<script>
export default {
 data(){
  return {
   nowDate: "",// 當前日期
   nowTime: "",// 當前時間
   nowWeek: ""   // 當前星期
  }
 },methods:{
  dealWithTime(data) { // 獲取當前時間
   let formatDateTime;
   let Y = data.getFullYear();
   let M = data.getMonth() + 1;
   let D = data.getDate();
   let H = data.getHours();
   let Min = data.getMinutes();
   let S = data.getSeconds();
   let W = data.getDay();
   H = H < 10 ? "0" + H : H;
   Min = Min < 10 ? "0" + Min : Min;
   S = S < 10 ? "0" + S : S;
   switch (W) {
    case 0:
     W = "日";
     break;
    case 1:
     W = "一";
     break;
    case 2:
     W = "二";
     break;
    case 3:
     W = "三";
     break;
    case 4:
     W = "四";
     break;
    case 5:
     W = "五";
     break;
    case 6:
     W = "六";
     break;
    default:
     break;
   }
   this.nowDate = Y + "年" + M + "月" + D + "日 ";
   this.nowWeek = "周" + W ; 
   this.nowTime = H + ":" + Min + ":" + S;
   // formatDateTime = Y + "年" + M + "月" + D + "日 " + " 周" +W + H + ":" + Min + ":" + S;
  },},mounted() { 
  // 頁面載入完後顯示當前時間
  this.dealWithTime(new Date())
  // 定時重新整理時間
  this.timer = setInterval(()=> {
    this.dealWithTime(new Date()) // 修改資料date
  },500)
 },destroyed() {
  if (this.timer) { // 注意在vue例項銷燬前,清除我們的定時器
   clearInterval(this.timer);
  }
 }
}
</script>

<style lang="scss" scope>

</style>

2. 實現效果

在這裡插入圖片描述

總結

到此這篇關於Vue 中獲取當前時間並實時重新整理的實現程式碼的文章就介紹到這了,更多相關vue獲取當前時間實時重新整理內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!