js获取当前时间并实时刷新1

显示代码

{{$moment(nowTime).format("YYYY-MM-DD HH:mm:ss")}} {{nowWeek}}

 data() {
    return {
      nowTime: new Date(),
      weekDays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
      timer: null
    };
  },
  mounted() {
    // 初始化时间
    this.init();
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  computed: {
    nowWeek() {
      return (this.nowTime && this.weekDays[this.nowTime.getDay()]) || "";
    }
  },
  methods: {
    init() {
      this.startTimer();
    },
    // 启动定时器,定时刷新时间
    startTimer() {
      this.nowTime = new Date();
      setTimeout(() => {
        this.nowTime = new Date();
        this.timer = setInterval(() => {
          this.nowTime = new Date();
        }, 1000);
      }, 1000 - this.nowTime.getMilliseconds());
    }
  }
posted @ 2022-04-12 19:51  寒冷的雨呢  阅读(877)  评论(0编辑  收藏  举报