[英]How to detect “net::ERR_CONNECTION_REFUSED”
The browser has a built in method called navigator.onLine
, which returns either true
or false
.浏览器有一个名为
navigator.onLine
的内置方法,它返回true
或false
。 Now to watch for connection changes you can add an event listener on window,现在要注意连接更改,您可以在 window 上添加事件侦听器,
window.addEventListener('offline', (e) => { console.log('offline'); });
window.addEventListener('online', (e) => { console.log('online'); });
You can incorporate this into a Vue component with something like:您可以将其合并到 Vue 组件中,例如:
export default {
data() {
return {
online: navigator.onLine
};
},
mounted() {
window.addEventListener("online", this.onchange);
window.addEventListener("offline", this.onchange);
this.onchange();
},
beforeDestroy() {
window.removeEventListener("online", this.onchange);
window.removeEventListener("offline", this.onchange);
},
methods: {
onchange() {
this.online = navigator.onLine;
this.$emit(this.online ? "online" : "offline");
}
}
};
And then use v-if="!online"
to selectively render you're offline banner.然后使用
v-if="!online"
选择性地呈现您的离线横幅。
Alternatively, take a look at: v-offline
, it instead works by pinging an endpoint, which has the advantage of being able to detect when the user is online but with very poor internet connection (loading), however is an overall less efficient approach.或者,看一下:
v-offline
,它通过 ping 端点来工作,其优点是能够检测用户何时在线但互联网连接(加载)非常差,但总体上是一种效率较低的方法.
import offline from 'v-offline';
export default {
components: {
offline
},
methods: {
handleConnectivityChange(status) {
console.log(status);
}
}
}
For most sock.js methods, you can get this information from the Event
parameter returned by the callback.对于大多数 sock.js 方法,您可以从回调返回的
Event
参数中获取此信息。 But for detecting network connection, and other common tasks, it's usually more robust to do natively, as outlined above.但是对于检测网络连接和其他常见任务,如上所述,在本机执行通常更健壮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.