实时显示当前时间

84 阅读1分钟

实现数据可视化页面时,需要界面上实时显示当前时间 实现效果为:年-月-日 时:分:秒 星期几

<div>{{ nowTime }}</div>
data() {
    return {
      nowTime: "",
    };
  },
 mounted() {
    this.nowTimes();
  },
 beforeDestroy() {
    this.clear();
  },
 methods: {
   timeFormate(timeStamp) {
      const date = new Date(timeStamp);
      const today = new Date().toLocaleDateString("zh-CN", { weekday: "long" });

      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hh = date.getHours().toString().padStart(2, "0");
      const mm = date.getMinutes().toString().padStart(2, "0");
      const ss = date.getSeconds().toString().padStart(2, "0");

      this.nowTime = `${year}-${month}-${day}\u3000${hh}:${mm}:${ss}\u3000${today}`;
    },
    // 启动定时器
    nowTimes() {
      // 立即执行一次格式化
      this.timeFormate(new Date());

      // 使用箭头函数绑定this,避免作用域问题
      this.timerId = setInterval(() => {
        this.timeFormate(new Date());
      }, 1000);
    },

    // 清除定时器
    clear() {
      clearInterval(this.timerId); // 通过正确的ID清除
      this.timerId = null; // 释放引用
    },
  },