vue使用setTimeout实现实时刷新,避免定时器死循环
1、定义变量timerval: null,isLeave: false2、在页面标签中添加 ref,获取页面dom元素,或者可以添加在需要定时刷新的dom元素上<div ref="timeouts"></div>3、定义自动刷新方法// 刷新,获取列表refresh() {this.getAIBoxPageList();},// 设置刷新内容setFresh() {if (
·
1、定义变量
timerval: null,
isLeave: false
2、在页面标签中添加 ref,获取页面dom元素,或者可以添加在需要定时刷新的dom元素上
<div ref="timeouts"></div>
3、定义自动刷新方法
// 刷新,获取列表
refresh() {
this.getAIBoxPageList();
},
// 设置刷新内容
setFresh() {
if (this.isLeave) return false;
let self = this;
let spacingTime = 10 * 1000;
// var timerval;
if (self.$refs.timeouts) {
if (self.$refs.timeouts) {
clearTimeout(self.timerval);
self.timerval = null;
self.isTimeout = true;
let that = self;
self.timerval = setTimeout(function timeout() {
that.refresh();
self.timerval = setTimeout(timeout, spacingTime);
}, spacingTime);
} else {
self.isTimeout = false;
}
self.$once("hook:beforeDestroy", () => {
clearTimeout(self.timerval);
});
} else {
clearTimeout(self.timerval);
self.timerval = null;
}
this.$once("hook:beforeDestroy", () => {
clearTimeout(self.timerval);
self.timerval = null;
});
},
4、在页面加载时,mounted生命周期中调用,监听浏览器tab标签切换事件
mounted() {
// 搜索,筛选,获取ai盒子分页列表
this.getAIBoxPageList();
// 刷新
this.setFresh();
let self = this;
document.addEventListener("visibilitychange", () => {
//浏览器tab标签切换事件
if (document.visibilityState == "hidden") {
//状态判断 没在当前页面呆着
console.log("离开了");
self.isLeave = true;
if (self.timerval) window.clearTimeout(self.timerval);
self.timerval = null;
} else {
//回来了
self.$once("hook:beforeDestroy", () => {
self.isLeave = true;
clearTimeout(self.timerval);
self.timerval = null;
});
console.log("回来了");
self.isLeave = false;
self.setFresh();
}
});
}
5、页面销毁前,清除延时器,定义beforeDestroy生命周期
beforeDestroy() {
this.isLeave = true;
clearTimeout(this.timerval);
this.timerval = null;
}
6、由于我开发的页面是有tab栏切换的,所以切换时需要清除或者重新添加定时刷新
// 切换选项卡
toggleTab(index) {
this.active = index;
if (this.active === 0) {
this.PageInfo.PageIndex = 1;
// 搜索,筛选,获取ai盒子分页列表
this.getAIBoxPageList();
this.isLeave = false;
this.setFresh()
} else if (this.active === 1) {
this.PageInfo1.PageIndex = 1;
// 获取教室列表(校区-教学楼-教室)
this.getQueryRoomModelList();
this.isLeave = true;
clearTimeout(this.timerval);
this.timerval = null;
}
},
更多推荐
已为社区贡献2条内容
所有评论(0)