场景:从含有定时器的页面切换到其他页面时,创建的定时器没有销毁,定时器继续执行,相应的事件也一直在进行;

换种说法:

tab一共有三个,分别对应其A页面、B页面、C页面,A页面中有个计时器,当切换tab到B页面或者C页面,A页面中的计时器必须要清除

页面展示:

解决方案:

import {onMounted, onBeforeUnmount} from 'vue'
   onBeforeUnmount(() => {
      console.log('mounted!')
      clearInterval(times)

    })

源代码:

     <div class="right">
                <span style="width: 105px;">自动刷新:{{timer}}</span><a-switch v-model="value" checked-value="yes" unchecked-value="no" @change="stop"></a-switch>
                <a-tooltip content="数据导出">
                  <a-button class="btn1"><icon-download :size="20" /></a-button>
                </a-tooltip>

     </div>
//倒计时
    const value=ref('yes')
    const timer = ref(200);
    let times=setInterval(timess,1000)
    function stop(){      
      if(value.value=='yes'){
        times=setInterval(timess,1000)
      }else{
        clearInterval(times)
      }
    }
    function timess(){
      if (timer.value === 0) {
          doRefresh()
          onSearchCount()
          timer.value = 200;
          return;
      }else {
          timer.value--;
        }
    }

   onBeforeUnmount(() => {
      console.log('mounted!')
      clearInterval(times)

    })

思路:

vue3版本:

与 2.x 版本生命周期相对应的组合式 API

  • beforeCreate -> 使用 setup()
  • created -> 使用 setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

setup相当于之前的created周期:创建时

        onBeforeMount:DOM即将挂载

        onMounted:DOM挂载完毕

        onBeforeUpdate:DOM即将更新

        onUpdated:DOM更新完毕

        onBeforeUnmount:即将销毁

        onUnmounted:销毁完毕

可以发现:

  1. beforeCreatecreatedsetup 几乎是同时进行的,所以可以把写在beforeCreatecreated 这两周期的代码直接写在 setup 里即可。
  2. 命名都形如 onXXX
  3. beforeDestroydestroyed 改为 onBeforeUnmountonUnmounted

Logo

前往低代码交流专区

更多推荐