vue清除间隔beforeDestroy

Vue clear interval beforeDestroy

我在一个运行良好的组件上有一个倒数计时器。问题是我希望在用户离开组件页面后停止间隔。我正在尝试在 beforeDestroy 挂钩中清除 clearInterval 但出于某种原因,我仍然每隔一秒从间隔中收到错误,并且它找不到 null 的 ID。这些错误只会在组件被销毁后发生。

<template>
  <div class="countdown">
    <img class="cover-image" src="@/assets/img/image_cover_image@2x.png" />
    <div class="countdown-container">
      <h2>Countdown to placeholder:</h2>
      <div class="counter">
        <div>
          <div id="day">0</div>
          Days
        </div>
        <div>
          <div id="hour">0</div>
          Hours
        </div>
        <div>
          <div id="minute">0</div>
          Minutes
        </div>
        <div>
          <div id="second">0</div>
          Seconds
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Countdown',
  data() {
    return {
      countDate: new Date('Jan 1, 2021 00:00:00:00').getTime(),
      counter: null,
    };
  },
  beforeCreate() {
    this.counter = setInterval(() => {
      const now = new Date().getTime();
      const gap = this.countDate - now;

      const second = 1000;
      const minute = second * 60;
      const hour = minute * 60;
      const day = hour * 24;

      let d = Math.floor(gap / day);
      let h = Math.floor((gap % day) / hour);
      let m = Math.floor((gap % hour) / minute);
      let s = Math.floor((gap % minute) / second);

      if (d <= 0 && h <= 0 && m <= 0 && s <= 0) {
        clearInterval(this.counter);
        d = 0;
        h = 0;
        m = 0;
        s = 0;
      }
      document.querySelector('#day').innerText = d;
      document.querySelector('#hour').innerText = h;
      document.querySelector('#minute').innerText = m;
      document.querySelector('#second').innerText = s;
    }, 1000);
  },
  beforeDestroy() {
    clearInterval(this.counter);
  },
};
</script>

我认为错误来自 beforeCreate 挂钩。在 beforeCreate 挂钩中,组件在 DOM.

中不可用

尝试将 beforeCreate 挂钩中的逻辑移动到 mounted 挂钩,当组件安装在 DOM 中时将调用该挂钩。