uni-app断开网络后export default内this调用不到方法

先上代码

<template>
	<view class="content">
		当前网络状态:{{isConnected}}
	</view>
</template>
<script>
	export default {
		data() {
			return {
				timer: null,
				isConnected:true,
			}
		},
		onLoad() {
			this.initPage()
		},
		methods: {
			 initPage(){
				 // 设置定时器,监听网络是否连接,3秒一次
				this.timer = setTimeout(()=>{
					this.networkChange()
				},3000)
			},
			networkChange(){
				uni.onNetworkStatusChange(function (res) {
					this.isConnected = res.isConnected
					if(res.isConnected){
						console.log("网络连接")
						this.consoleLog()
					}else{
						console.log("网络断开")
						this.consoleLog()
					}
				});
			},
			consoleLog(){
				console.log("aaaaaaaa")
			}
			
		}
	}
</script>
<style>	
</style>

此时,如果把网络断开,控制台报错(我是真机调试,因为浏览器不太好模拟断网状态

[Vue warn]: Error in event handler for “api.onNetworkStatusChange”:
“TypeError: Cannot set property ‘isConnected’ of undefined” (found <
root >) TypeError: Cannot set property ‘isConnected’ of undefined

回复网络连接后依然报这个错,大概猜测了下,断网后this似乎“消失”了,即便重新连接,也没有恢复
于是试着把 this 保存到 export default 的外面,发现问题解决
在这里插入图片描述
在这里插入图片描述
修改后的代码

<template>
	<view class="content">
		当前网络状态:{{isConnected}}
	</view>
</template>

<script>
	let that
	export default {
		data() {
			return {
				timer: null,
				isConnected:true,
			}
		},
		onLoad() {
			that = this
			that.initPage()
		},
		methods: {
			 initPage(){
				 // 设置定时器,监听网络是否连接,3秒一次
				that.timer = setTimeout(()=>{
					that.networkChange()
				},3000)
			},
			networkChange(){
				uni.onNetworkStatusChange(function (res) {
					that.isConnected = res.isConnected
					if(res.isConnected){
						console.log("网络连接")
						that.consoleLog()
					}else{
						console.log("网络断开")
						that.consoleLog()
					}
				});
			},
			consoleLog(){
				console.log("aaaaaaaa")
			}
			
		}
	}
</script>
<style>
</style>

前端菜鸟小白,如果有知道原因的还望告诉我,谢谢~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值