vue项目中轮询状态更改

在实际项目中,对于实时存储改变的数据,如果不是使用websoct,就需要使用到轮询,对于轮询实际是前端设置的定时器,不停存储获取数据并进行更改。

而对于退出该界面后,轮询逻辑依然在定时器的执行中进行,此时需要用到钩子函数判断路由离开状态后,进行清除定时器

 //离开当前页面
beforeRouteLeave(to, from, next) {
window.clearInterval(this.myInterval);
//清除定时器
next();
},

vue轮询方法及清除

<script>
var Vue = new Vue({
el: '#app',
data: {
timer: null,
},
created() {
this.pollfun()
},
methods: {
//轮询
pollfun() {
this.timer = window.setInterval(() => {
setTimeout(() => {
this.getDetes()
}, 0)
}, 3000)
},
//清除轮询
clearfun() {
clearInterval(this.timer);
this.timer = null;
}
},
//离开页面清除
destroyed() {
window.clearInterval(this.timer)
}
})
</script>

destroyed 是监听页面销毁钩子函数

以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。