一、js源代码

声明变量

  export default {
    data() {
      return {
        timer: "", //定义一个定时器
        nowTime: "",
      }
    }
  }

获取时间

      getTime() {
        this.timer = setInterval(() => {
          let timeDate = new Date();
          let year = timeDate.getFullYear();
          let mounth = timeDate.getMonth() + 1;
          let day = timeDate.getDate();
          let hours = timeDate.getHours();
          hours = hours >= 10 ? hours : "0" + hours;
          let minutes = timeDate.getMinutes();
          minutes = minutes >= 10 ? minutes : "0" + minutes;
          let seconds = timeDate.getSeconds();
          seconds = seconds >= 10 ? seconds : "0" + seconds;
          let week = timeDate.getDay();
          let weekArr = [
            "星期日",
            "星期一",
            "星期二",
            "星期三",
            "星期四",
            "星期五",
            "星期六",
          ];

 		  this.nowTime = `${year}/${mounth}/${day} ${hours}:${minutes}:${seconds} ${weekArr[week]}`
        }, 1000);
      }

setInterval销毁

if (this.timer) {
  clearInterval(this.timer);
}

二、效果图

image-1667802902866