VUE 轮询/轮询终止 beforeRouteLeave

科技资讯 投稿 7200 0 评论

VUE 轮询/轮询终止 beforeRouteLeave

目录

2 在methods中定义

4 终止轮询

方法二: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{ // 路由跳转前,清除轮询
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; } },

结尾🔚

本文主要是向介绍了用的很少的钩子函数(关键时候是真好使啊)

编程笔记 » VUE 轮询/轮询终止 beforeRouteLeave

赞同 (29) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽