记一次vue3页面倒计时(定时器)切换页面问题
场景:从含有定时器的页面切换到其他页面时,创建的定时器没有销毁,定时器继续执行,相应的事件也一直在进行;onBeforeUpdate:DOM即将更新。onBeforeMount:DOM即将挂载。onBeforeUnmount:即将销毁。onMounted:DOM挂载完毕。onUpdated:DOM更新完毕。setup相当于之前的created周期:创建时。onUnmounted:销毁完毕。与 2.
·
场景:从含有定时器的页面切换到其他页面时,创建的定时器没有销毁,定时器继续执行,相应的事件也一直在进行;
换种说法:
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:销毁完毕
可以发现:
beforeCreate
和created
与setup
几乎是同时进行的,所以可以把写在beforeCreate
和created
这两周期的代码直接写在setup
里即可。- 命名都形如
onXXX
。beforeDestroy
和destroyed
改为onBeforeUnmount
和onUnmounted
。
更多推荐
已为社区贡献4条内容
所有评论(0)