全局監(jiān)聽
App({
globalData: {
nonetwork: false //判斷是否有網(wǎng)絡(luò)
},
onShow() {
this.onNetworkStatusChange() //開啟檢測
},
onNetworkStatusChange() {
var that = this
//獲取網(wǎng)絡(luò)類型
wx.getNetworkType({
success: function (res) {
const networkType = res.networkType
//不為none代表有網(wǎng)絡(luò)
if ('none' != networkType) {
that.globalData.nonetwork = true
//網(wǎng)絡(luò)狀態(tài)變化事件的回調(diào)函數(shù) 開啟網(wǎng)絡(luò)監(jiān)聽持钉,監(jiān)聽小程序的網(wǎng)絡(luò)變化
wx.onNetworkStatusChange(function (res) {
if (res.isConnected) {
//網(wǎng)絡(luò)變?yōu)橛芯W(wǎng)
that.globalData.nonetwork = true
} else {
//網(wǎng)絡(luò)變?yōu)闊o網(wǎng)
that.globalData.nonetwork = false
}
})
} else {
//無網(wǎng)狀態(tài)
wx.onNetworkStatusChange(function (res) {
if (res.isConnected) {
that.globalData.nonetwork = true
} else {
that.globalData.nonetwork = false
}
})
}
},
})
}
})
app.js
頁面使用
const app = getApp()
Page({
data: {
nonetwork: false
},
onLoad() {
//判斷是否網(wǎng)絡(luò)
if (app.globalData.nonetwork) {
this.setData({
nonetwork: true
})
//添加轉(zhuǎn)圈
wx.showLoading({
title: "獲取數(shù)據(jù)中!"
});
} else {
this.setData({
nonetwork: false
})
wx.showToast({
title: '請連接網(wǎng)絡(luò)',
icon: 'none',
duration: 2000
})
}
},
doRefresh() {
//無網(wǎng)絡(luò)的刷新
this.onLoad()
}
})
index.js
<view wx:if="{{nonetwork}}">
內(nèi)容
</view>
<view wx:else>
<button bindtap="doRefresh">刷新</button>
</view>
index.wxml