• VUE设置和清除定时器


    方法一、在生命周期函数beforeDestroy中清除 

    1. data() {
    2. return {
    3. timer: null;
    4. };
    5. },
    6. created() {
    7. // 设置定时器,5s执行一次
    8. this.timer = setInterval(() => {
    9. console.log('setInterval');
    10. }, 5000);
    11. }
    12. beforeDestroy () {
    13. //清除定时器
    14. clearInterval(this.timer);
    15. this.timer = null;
    16. }

    方法二、使用hook:beforedestroy(推荐)

    1. created() {
    2. // 设置定时器,5s执行一次
    3. let timer = setInterval(() => {
    4. console.log('setInterval');
    5. }, 5000);
    6. // 离开当前页面时销毁定时器
    7. this.$once('hook:beforeDestroy', () => {
    8. clearInterval(timer);
    9. timer = null;
    10. })
    11. }

    该方法与在生命周期钩子beforeDestroy中清除定时器的操作原理一样,但更有优势

    1.无需在vue实例上定义定时器,减少不必要的内存浪费

    2.设置和清除定时器的代码放在一块,可读性维护性更好

    三、beforeDestroy函数没有触发的情况

    1、原因

    <router-view>外层包裹了一层

    < keep-alive > 有缓存的作用,可以使被包裹的组件状态维持不变,当路由被 keep-alive 缓存时不走 beforeDestroy 生命周期。被包含在 < keep-alive > 中创建的组件,会多出两个生命周期钩子: activated 与 deactivated。

    activated
    在组件被激活时调用,在组件第一次渲染时也会被调用,之后每次keep-alive激活时被调用。

    deactivated
    在组件失活时调用。

    2、解决方案

    借助 activated 和 deactivated 钩子来设置和清除定时器

    (1)生命周期钩子

    1. created() {
    2. // 页面激活时设置定时器
    3. this.$on("hook:activated", () => {
    4. let timer = setInterval(()=>{
    5. console.log("setInterval");
    6. },1000)
    7. })
    8. // 页面失活时清除定时器
    9. this.$on("hook:deactivated", ()=>{
    10. clearInterval(timer);
    11. timer = null;
    12. })
    13. }

    (2)hook

    1. data() {
    2. return {
    3. timer: null // 定时器
    4. }
    5. },
    6. activated() {
    7. // 页面激活时开启定时器
    8. this.timer = setInterval(() => {
    9. console.log('setInterval');
    10. }, 5000)
    11. },
    12. deactivated() {
    13. // 页面关闭(路由跳转)时清除定时器
    14. clearInterval(this.timer)
    15. this.timer = null
    16. },
  • 相关阅读:
    制造业单项冠军(国家级、广东省、深圳市)奖励政策及申报对比
    五:Dubbo中Provider参数配置及源码讲解
    Java基础----多线程
    Linux学习笔记——文件的查找与检索
    tictoc 例子理解 13-15
    架构——方法多态(重载)
    Linux——指令初识(二)
    (二) Docker安装
    redis缓存穿透、击穿、雪崩介绍
    python忽略警告信息
  • 原文地址:https://blog.csdn.net/marsur/article/details/127536322