zoukankan      html  css  js  c++  java
  • vue中清除定时器的高阶方法

    程序化的事件侦听器

    比如,在页面挂载时定义计时器,需要在页面销毁时清除定时器。这看起来没什么问题。但仔细一看 this.timer 唯一的作用只是为了能够在 beforeDestroy 内取到计时器序号,除此之外没有任何用处。

    export default {
        mounted() {
            this.timer = setInterval(() => {
                console.log(Date.now())
            }, 1000)
        },
        beforeDestroy() {
            clearInterval(this.timer)
        }
    }
    

    如果可以的话最好只有生命周期钩子可以访问到它。这并不算严重的问题,但是它可以被视为杂物。

    我们可以通过 $on$once 监听页面生命周期销毁来解决这个问题:

    export default {
        mounted() {
            this.creatInterval('hello')
            this.creatInterval('world')
        },
        creatInterval(msg) {
            let timer = setInterval(() => {
                console.log(msg)
            }, 1000)
            this.$once('hook:beforeDestroy', function() {
                clearInterval(timer)
            })
        }
    }
    
    

    使用这个方法后,即使我们同时创建多个计时器,也不影响效果。因为它们会在页面销毁后程序化的自主清除。

  • 相关阅读:
    浏览器组成
    Go!!!
    产假计算器地址
    flex 纵向布局,垂直换行,没有撑开父盒子宽度,求解??
    毕业档案
    进程与线程
    事件循环
    回调地狱
    错误优先回调
    组件 v-if 小心哦
  • 原文地址:https://www.cnblogs.com/wangqingjiu/p/12836445.html
Copyright © 2011-2022 走看看