为什么 beforeDestroyed 函数不起作用?

问题描述

我有一个mounted() 钩子中调用方法,它使用 setInterval 来设置时间间隔,如下所示:

methods: {
  clock() {     
    const date = new Date()

    const hours = ((date.getHours() + 11) % 12 + 1);
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();

    const hour = hours * 30;
    const minute = minutes * 6;
    const second = seconds * 6;
}},mounted: function() {
  setInterval(this.clock,1000);
},

还有一个函数可以清除 beforeDestroyed 钩子中的间隔。 console.log 输出“workBefore”,所以我知道它正在进入函数内部,但没有清除间隔。下面是函数

beforeDestroyed: function() {
  console.log("workBefore")
    clearInterval(this.clock);
  }

感谢任何帮助!!!

解决方法

setInterval 返回一个区间,用于清除区间,这意味着你需要将setInterval的返回值存储到一个变量中,同时在data中定义该变量对象,因此它可以在组件中的任何地方访问。

this.interval = setInterval(this.clock,1000);

然后,使用 this.interval 清除 beforeDestroy 中的间隔。

clearInterval(this.interval);
,

如果您所做的只是清除间隔,则下面的答案不需要您有 beforeDestroy 钩子。

mounted() {
  const interval = setInterval(this.clock,1000);
    this.$once('hook:beforeDestroy',() => {
       clearInterval(interval);
    })

},