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) 推荐
beforeRouteLeave(to, from, next){ // 路由跳转前,清除轮询 next(); if (this.polling) { clearInterval(this.polling); this.polling = null; } },
所有代码
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