VUE 轮询、轮询终止 beforeRouteLeave
目录
1 在data中定义
2 在methods中定义
3 开始轮询
4 终止轮询
方法一: destroyed()
方法二:beforeRouteLeave(to, from, next) 推荐
所有代码
轮询:polling
1 在data中定义
data() { return { polling: '' } },
2 在methods中定义
methods: { getDateLoop(timeout = 15000) { // timeout可以写死,也可以动态 console.log('查询'); // 执行语句 this.polling = setInterval(() => { console.log('查询'); // 轮询中,执行语句 }, timeout) }, },
3 开始轮询
created() { this.getDateLoop(); // 开始轮询 },
在当前页面不停打印,说明轮询成功
4 终止轮询
方法一: destroyed()
这个方法,反复跳转后会失效(有点奇怪),所以转用方法二
失效原因:开发的网页是SPA-单页面应用,每次页面跳转,都是由路由机制管理,刷新的只有网页内容。(因为这个销毁过程失灵时不灵,所以博主猜测:)页面跳转的时候不一定会销毁这个组件所以这个方法失灵时不灵。
destroyed() { clearInterval(this.polling) // 结束轮询 },
跳转页面后,停止打印,说明轮询停止
方法二:beforeRouteLeave(to, from, next) 推荐
1 2 3 4 5 6 7 | beforeRouteLeave(to, from, next){ // 路由跳转前,清除轮询 next(); if ( this .polling) { clearInterval( this .polling); this .polling = null ; } }, |
所有代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | data() { return { polling: '' } }, methods: { getDateLoop(timeout = 15000) { // timeout可以写死,也可以动态 console.log( '查询' ); // 执行语句 this .polling = setInterval(() => { console.log( '查询' ); // 轮询中,执行语句 }, timeout) }, }, created() { this .getDateLoop(); // 开始轮询 }, // destroyed() { // clearInterval(this.polling) // 结束轮询 // }, beforeRouteLeave(to, from, next){ // 路由跳转前,清除轮询 next(); if ( this .polling) { clearInterval( this .polling); this .polling = null ; } }, |
结尾🔚
本文主要是向介绍了用的很少的钩子函数(关键时候是真好使啊)
本文来自博客园,作者:喆星高照,转载请注明原文链接:https://www.cnblogs.com/houxianzhou/p/17086505.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?