navigator.onLine //false true
检测当前是否有网
var connection = navigator.connection;
var type = connection.effectiveType;
function updateConnectionStatus() {
console.log("网络状况从 " + type + " 切换至" + connection.effectiveType);
type = connection.effectiveType;
}
connection.addEventListener('change', updateConnectionStatus);
监听变更之后,我们可以弹一个Modal提醒用户,也可以出一个Notice通知用户网络有变化,或者可以更高级得去自动切换清晰度(这个应该比较难)。
vue中断网提示
引用组件
<OfflineHandle
offlineTitle = "断网处理标题"
desc="断网处理描述"
onlineTitle="连网提醒"
/>
组件
<!--OfflineHandle.vue-->
<template>
<div v-if="mask" class="offline-mask">
<h2 class="offline-mask-title">{{ offlineTitle }}</h2>
<p class="offline-mask-desc">{{ desc }}</p >
</div>
</template>
<script>
export default {
name: "offline-handle",
props: {
offlineTitle: {
type: String,
default: "网络已断开,请检查网络连接。",
},
onlineTitle: {
type: String,
default: "网络已连接",
},
desc: {
type: String,
default: "",
},
duration: {
type: Number,
default: 4.5,
},
},
data() {
return {
mask: false,
};
},
mounted() {
window.addEventListener("offline", this.eventHandle);
window.addEventListener("online", this.eventHandle);
console.log(this.desc);
},
beforeDestroy() {
window.removeEventListener("offline", this.eventHandle);
window.removeEventListener("online", this.eventHandle);
},
methods: {
eventHandle(event) {
const type = event.type === "offline" ? "error" : "success";
this.$Notice[type]({
title: type === "error" ? this.offlineTitle : this.onlineTitle,
desc: type === "error" ? this.desc : "",
duration: this.duration,
});
setTimeout(() => {
this.mask = event.type === "offline";
}, 1500);
},
},
};
</script>
<style lang="css" scoped>
.offline-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
z-index: 9999;
transition: position 2s;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.offline-mask-title {
color: rgba(0, 0, 0, 0.8);
}
.offline-mask-desc {
margin-top: 20px;
color: red;
font-weight: bold;
}
</style>