【问题标题】:Vue update dom every second, Simple ClockVue每秒更新dom,简单时钟
【发布时间】:2020-05-25 23:03:44
【问题描述】:

我正在尝试制作简单的时钟,我使用@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

【问题讨论】:

  • 您的 style 标签中有错字 - 应该是 .container 而不是 .contaienr

标签: javascript typescript vuejs2 vue-component


【解决方案1】:

您正在创建一个新日期并每秒引用一次(它永远不会改变) - 相反,在 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;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2018-02-17
    • 2021-12-01
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多