vue定时器定时执行任务(VUE设置和清除定时器)
导读:方法一、在生命周期函数beforeDestroy中清除 data( { return...
方法一 、在生命周期函数beforeDestroy中清除
data() { return { timer: null; }; }, created() { // 设置定时器 ,5s执行一次 this.timer = setInterval(() => { console.log(setInterval); }, 5000); } beforeDestroy () { //清除定时器 clearInterval(this.timer); this.timer = null; }方法二 、使用hook:beforedestroy(推荐)
created() { // 设置定时器 ,5s执行一次 let timer = setInterval(() => { console.log(setInterval); }, 5000); // 离开当前页面时销毁定时器 this.$once(hook:beforeDestroy, () => { clearInterval(timer); timer = null; }) }该方法与在生命周期钩子beforeDestroy中清除定时器的操作原理一样 ,但更有优势
1.无需在vue实例上定义定时器 ,减少不必要的内存浪费
2.设置和清除定时器的代码放在一块 ,可读性维护性更好
三 、beforeDestroy函数没有触发的情况
1 、原因
<router-view>外层包裹了一层<keep-alive>
< keep-alive > 有缓存的作用 ,可以使被包裹的组件状态维持不变 ,当路由被 keep-alive 缓存时不走 beforeDestroy 生命周期 。被包含在 < keep-alive > 中创建的组件 ,会多出两个生命周期钩子: activated 与 deactivated 。
activated 在组件被激活时调用 ,在组件第一次渲染时也会被调用 ,之后每次keep-alive激活时被调用 。
deactivated 在组件失活时调用 。
2 、解决方案
借助 activated 和 deactivated 钩子来设置和清除定时器
(1)生命周期钩子
created() { // 页面激活时设置定时器 this.$on("hook:activated", () => { let timer = setInterval(()=>{ console.log("setInterval"); },1000) }) // 页面失活时清除定时器 this.$on("hook:deactivated", ()=>{ clearInterval(timer); timer = null; }) }(2)hook
data() { return { timer: null // 定时器 } }, activated() { // 页面激活时开启定时器 this.timer = setInterval(() => { console.log(setInterval); }, 5000) }, deactivated() { // 页面关闭(路由跳转)时清除定时器 clearInterval(this.timer) this.timer = null },创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!