先上代码
<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>
前端菜鸟小白,如果有知道原因的还望告诉我,谢谢~