页面数据定时刷新问题
在我们前端工作中,如果条件不允许使用websocket,或者暂时为演示项目,让我们暂时使用定时刷新,来保持项目的页面数据的刷新。
以uniapp为例,这里做一个示范,有问题,请评论纠正,谢谢。
步骤一 定义变量 autoRefreshId,theTime
autoRefreshId:1 ,// 判断自动刷新 1 刷新,0 停止
theTime:'',
步骤二 使用settimeout
在你需要刷新数据的地方使用settimeout
例如
if (that.autoRefreshId == 1) {
that.theTime = setTimeout(() => {
that.getDevDtData();
}, 3000);
}else{
clearTimeout(that.theTime)
}
我在数据请求成功之后使用setTimeout 将setTimeout事件赋值给theTime 变量(方便后面清除)
步骤三 清除setTimeout
以uniapp为例
我在onhide和onUnload事件都写入清除事件(即 页面销毁 和 页面隐藏 事件都要加上清除定时)
this.autoRefreshId = 0;// 同时改变autoRefreshId 数值
clearTimeout(this.theTime) // 清除指定的定时setTimeout
clearTimeout()// 清除所有setTimeout
然后就能够实现数据刷新的效果。
注意: 如果使用到v-for 则将DOM的key好好设置一下,不然会使得用户感受到页面DOM刷新。