App({ globalData: { nonetwork: false //判断是否有网络 }, onShow() { this.onNetworkStatusChange() //开启检测 }, onNetworkStatusChange() { var that = this //获取网络类型 wx.getNetworkType({ success: function (res) { const networkType = res.networkType //不为none代表有网络 if ('none' != networkType) { that.globalData.nonetwork = true //网络状态变化事件的回调函数 开启网络监听,监听小程序的网络变化 wx.onNetworkStatusChange(function (res) { if (res.isConnected) { //网络变为有网 that.globalData.nonetwork = true } else { //网络变为无网 that.globalData.nonetwork = false } }) } else { //无网状态 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() { //判断是否网络 if (app.globalData.nonetwork) { this.setData({ nonetwork: true }) //添加转圈 wx.showLoading({ title: "获取数据中!" }); } else { this.setData({ nonetwork: false }) wx.showToast({ title: '请连接网络', icon: 'none', duration: 2000 }) } }, doRefresh() { //无网络的刷新 this.onLoad() } }) |
index.js
<view wx:if="{{nonetwork}}"> 内容 </view> <view wx:else> <button bindtap="doRefresh">刷新</button> </view> |