想要在vue3里实现定时任务,定时刷新,定时发送请求等等,我们需要借助window对象中的setInterval方法,关于这个方法的具体介绍参考这里Window setInterval() 方法。
一、具体代码实现
<template>
<div>
<div id="l1">
<!-- 页面代码 -->
</div>
</div>
</template>
<script>
import { defineComponent, onMounted, ref, onDeactivated } from 'vue';
export default defineComponent({
setup() {
const timer = ref(0)
const index = ref(0)
onMounted(()=>{ //组件挂载时的生命周期执行的方法
timer.value = window.setInterval(function logname() {
// 其他定时执行的方法
index.value = index.value + 1
console.log("测试"+ index.value);
}, 3000);
})
onDeactivated(()=>{ //离开当前组件的生命周期执行的方法
window.clearInterval(timer.value);
})
}
})
</script>