通用方法,Html5在window.navigator對象上添加了一個屬性onLine 返回布爾值 true表示在線.同時新增了兩個事件:
window.addEventListener('online', function(){ // 網絡由異常到正常時觸發 }); window.addEventListener('offline', function(){ // 網絡由正常常到異常時觸發 });
在vue中實現思路如下:
data中初始化在線狀態。
data(){ return{ onLine: navigator.onLine, } }
mounted中監聽事件
mounted(){ window.addEventListener('online', this.updateOnlineStatus); window.addEventListener('offline', this.updateOnlineStatus); }
方法中改變onLine值
methods:{ updateOnlineStatus(e) { const { type } = e; this.onLine = type === 'online'; }, }
4.最后 最好在銷毀時解除事件監聽
beforeDestroy(){ window.removeEventListener('online', this.updateOnlineStatus); window.removeEventListener('offline', this.updateOnlineStatus); },
作者:黎明破曉的街道
鏈接:https://juejin.im/post/5bfccaa5e51d452c6061f599
另外也可以采用H5的API拓展plusready來實現
http://www.html5plus.org/doc/zh_cn/events.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Events Example</title> <script type="text/javascript" > // 擴展API加載完畢后調用onPlusReady回調函數 document.addEventListener("plusready", onPlusReady, false); function onPlusReady(){ document.addEventListener("netchange", onNetChange, false); } function onNetChange(){ var nt = plus.networkinfo.getCurrentType(); switch (nt){ case plus.networkinfo.CONNECTION_ETHERNET: case plus.networkinfo.CONNECTION_WIFI: alert("Switch to Wifi networks!"); break; case plus.networkinfo.CONNECTION_CELL2G: case plus.networkinfo.CONNECTION_CELL3G: case plus.networkinfo.CONNECTION_CELL4G: alert("Switch to Cellular networks!"); break; default: alert("Not networks!"); break; } } </script> </head> <body > </body> </html>
摘自:https://blog.csdn.net/weixin_38291260/article/details/89226854