data(){
return{
onLine: navigator.onLine,
}
},
mounted(){
window.addEventListener(‘online‘,this.updateOnlineStatus);
window.addEventListener(‘offline‘,this.updateOnlineStatus);
},
methods:{
updateOnlineStatus(e) {
const { type } = e;
this.onLine = type ===‘online‘;
if (!this.onLine) {
this.$toast({
message: "当前网络异常",
position: "middle",
duration: 1500
})
}
},
},
//在销毁时解除事件监听
beforeDestroy(){
window.removeEventListener(‘online‘,this.updateOnlineStatus);
window.removeEventListener(‘offline‘,this.updateOnlineStatus);
},
原文:https://www.cnblogs.com/chicidol/p/15062853.html