【问题标题】:Why is beforeDestroyed function not working?为什么 beforeDestroyed 函数不起作用?
【发布时间】:2021-08-20 20:27:16
【问题描述】:

我有一个在 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);
  }

感谢任何帮助!!!

【问题讨论】:

    标签: javascript vue.js lifecycle


    【解决方案1】:

    setInterval返回一个区间,用于清除区间,也就是说你需要将setInterval返回的值存储到一个变量中,还要在data对象中定义这个变量,这样才能访问组件中的任何位置。

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

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

    clearInterval(this.interval);
    

    【讨论】:

    • 谢谢!结果很好。但是,您在 clearInterval 部分中创建了我认为的类型。这需要以 this.interval 作为参数。
    【解决方案2】:

    如果您所做的只是清除间隔,则以下答案不需要您使用 beforeDestroy 挂钩。

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

    【讨论】:

      猜你喜欢
      • 2014-08-06
      • 2015-02-20
      • 2021-07-25
      • 2013-08-26
      • 2011-11-13
      • 2023-03-15
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多