Vue 脚手架项目,轮询完整实现,适合新消息刷新等逻辑

Vue 脚手架项目,轮询完整实现,适合新消息刷新等逻辑

已实现逻辑

1. 轮询
2. 调用
3. 重连
4. 时序性

/**** App.vue ****/
<script>
	/* 失败时,设置三次重连 */
	let errCount = 3
	export default {
		data() {
			return {
				timer: null,
				token: 'token',
				errCount 
			}
		},
		watch: {
			/* 监听用户登录是否有效 */
			token: {
				handler(){
					if (this.token) { /* 当用户登录有效时发起请求 */
						this.request()
						this.$once("hook:beforeDestroy", ()=>{ /* 组件销毁前进行定时清除 */
							clearTimeout(this.timer)
						})
					} else {
						clearTimeout(this.timer)
					}
				},
				immediate: true
			}
		},
		methods: {
			request() {
				/* 当拿到响应后,进行polling,顺延15秒再次发起求,避免服务器已经停止工作或响应慢时频繁发起请求 */
				getMessage()
					.then(()=>{
						/* 恢复重连次数 */
						this.errCount = errCount
						
						/********
								业务逻辑
										********/
										
						this.polling()
					})
					.catch(err=>{
						if (this.errCount) {
							/* 每失败一次,进行一次减减 */
							this.errCount--
							this.polling()
						} else {
							/* 提示刷新页面或查看网络连接 */
						}
					})
			},
			polling(){
				/* 调用前进行定时清除 */
				clearTimeout(this.timer)
				this.timer = setTimeout(this.request, 1000 * 15 /* 15秒 */)
			}
		}
	}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值