vue3 URL变动时清空setInterval
在 Vue 3 中,可以使用 onBeforeUnmount 钩子来清除 setInterval。当组件被卸载时,该钩子会自动调用,并且可以在其中清除 setInterval。以下是示例代码:
<template>
<div>
<p>{{ count }}</p>
</div>
</template>
<script>
import { onMounted, onBeforeUnmount, ref } from 'vue'
export default {
setup() {
const count = ref(0)
let intervalId = null
const startInterval = () => {
intervalId = setInterval(() => {
count.value++
}, 1000)
}
onMounted(() => {
startInterval()
})
onBeforeUnmount(() => {
clearInterval(intervalId)
})
return {
count
}
}
}
</script>
在上面的示例中,onMounted 钩子会在组件挂载时调用 startInterval 方法,该方法将 setInterval 赋值给 intervalId 变量。然后,onBeforeUnmount 钩子会在组件卸载时调用 clearInterval 方法来清除 intervalId 变量的值。
这样,当组件被卸载时,就会清除 setInterval。
原文地址: http://www.cveoy.top/t/topic/f2Z 著作权归作者所有。请勿转载和采集!