小程序模板網(wǎng)

微信小程序?qū)崟r(shí)監(jiān)測網(wǎng)絡(luò)狀態(tài)變化

發(fā)布時(shí)間:2021-06-23 14:44 所屬欄目:小程序開發(fā)教程
全局監(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>


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://22321a.com/wxmini/doc/course/26706.html 復(fù)制鏈接 如需定制請聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢