Vue обновлять дом каждую секунду, простые часы - PullRequest
0 голосов
/ 10 февраля 2020

Я пытаюсь сделать простые часы, я создал проект, используя @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.

1 Ответ

2 голосов
/ 10 февраля 2020

Вы создаете новую дату один раз и ссылаетесь на нее каждую секунду (она никогда не меняется) - вместо этого создайте новую ссылку в 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;
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...