首页 > 解决方案 > Vue每秒更新dom,简单时钟

问题描述

我正在尝试制作简单的时钟,我使用创建的项目@vue/cli,目前有两个文件App.vue,它们只是其他组件的主机/视图,clock.vue内部导入App.vue的组件和时钟组件代码如下。

    <template>
      <div class="container">
        <div class="vertical">
          {{ hours }}
          <br />
          {{ minutes }}
          <br />
          {{ seconds }}
          <br />
          {{ amPm }}
        </div>
        <div class="horizontal">
          {{ hours }} : {{ minutes }} : {{ seconds }} : {{ amPm }}
        </div>
      </div>
    </template>

    <script lang="ts">
    import Vue from "vue";

    const date = new Date();
    export default Vue.extend({
      data() {
        return {
          hours: date.getHours(),
          minutes: date.getMinutes(),
          seconds: date.getSeconds(),
          amPm: "AM",
          interval: 0
        };
      },
      mounted() {
        this.interval = setInterval(this.updateClock, 1000);
      },
      beforeDestroy() {
        clearInterval(this.interval);
      },

      methods: {
        updateClock(): void {
          this.hours = date.getHours();
          this.minutes = date.getMinutes();
          this.seconds = date.getSeconds();
          this.amPm = this.hours >= 12 ? "PM" : "AM";
          this.hours = this.hours % 12 || 12;
          this.minutes = this.minutes < 10 ? 0 + this.minutes : this.minutes;
          this.hours = this.hours < 10 ? 0 + this.hours : this.hours;
        }
      }
    });
    </script>

    <style lang="scss">
    .contaienr {
      display: flex;
    }
    </style>

我希望时钟每秒更新一次,setInterval但由于某种原因它仍然无法正常工作。检查了很多关于 stackoverflow 的答案,他们都使用setInterval.

标签: javascripttypescriptvuejs2vue-component

解决方案


您正在创建一个新日期并每秒引用一次(它永远不会改变) - 相反,在其中创建一个新引用updateClock并删除另一个:

methods: {
  updateClock(): void {
    const date = new Date(); // create a new reference here

    this.hours = date.getHours();
    this.minutes = date.getMinutes();
    this.seconds = date.getSeconds();
    this.amPm = this.hours >= 12 ? "PM" : "AM";
    this.hours = this.hours % 12 || 12;
    this.minutes = this.minutes < 10 ? 0 + this.minutes : this.minutes;
    this.hours = this.hours < 10 ? 0 + this.hours : this.hours;
  }
}

推荐阅读