1.HTML5 api实时更新断网状态
// 当在线 / 离线状态切换时,online/offline 事件将触发在 body 元素上,
// 并且沿着 document.body,document 和 window 的顺序冒泡。
// 因此,开发者可以通过监听它们的 online/offline 事件来获悉网络状态。
window.addEventListener('online', ()=> {
alert('在线')
});
window.addEventListener('offline', ()=> {
alert('断网')
});
2.组件
<template>
<!-- 断网提示 -->
<div class="miz-is-online" :class="customClass" v-show="!isOnline"><slot>{{onlineText}}</slot></div>
</template>
<script>
export default {
props: {
customClass: {
type: String,
default: ''
},
onlineText: {
type: String,
default: '网络已断开或者移动网络被限制'
}
},
data() {
return {
isOnline: true
}
},
mounted() {
// 判断是否断网
window.addEventListener('online', this.online);
window.addEventListener('offline', this.offline);
this.networkStatus(true);
},
methods: {
online () {
this.isOnline = true;
this.networkStatus(true);
},
offline (){
this.isOnline = false;
this.networkStatus(false);
},
networkStatus (flag) {
this.$emit('networkStatus', flag);
}
},
beforeDestroy (){
// 取消监听
window.removeEventListener('online', this.online);
window.removeEventListener('offline', this.offline);
}
};
</script>
<style lang="scss">
.miz-is-online {
z-index: 1000000;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 70px;
line-height: 70px;
background: #f4c1ca;
font-size: 18px;
padding-left: 40px;
&::before {
content: "!";
display: inline-block;
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
margin-right: 20px;
border-radius: 50%;
color: #fff;
background: red;
}
}
</style>
3.目的 主要是为了在用户做一些操作的时候突然间断网,能够提示到他操作是不生效的,能够避免一些情况