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)
            })
        }
    }
    
    

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

  • 相关阅读:
    BZOJ 1565 植物大战僵尸
    BZOJ 1497 最大获利(最大权闭合子图)
    BZOJ 1070 修车(最小费用流)
    BZOJ 2879 NOI2012美食节
    PHPCMS模板里面使用自定义函数
    邓_phpcms_数据库
    邓_ phpcms_
    dedecms====phpcms 区别==[工作]
    邓_html_图片轮播
    dedecms_插件
  • 原文地址:https://www.cnblogs.com/wangqingjiu/p/12836445.html
Copyright © 2011-2022 走看看