![cover](https://img-blog.csdnimg.cn/img_convert/a7b426f027554ddcbce196b962043da2.png)
vue中如何利用js如何检测网络状况,监听网络状态
一、通用方法,Html5在window.navigator对象上添加了一个属性onLine 返回布尔值 true表示在线.同时新增了两个事件:window.addEventListener('online',function(){// 网络由异常到正常时触发});window.addEventListener('offline', function(){// 网络由正常常到异常时触发});复制代码
·
一、通用方法,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';
},
}
- 最后 最好在销毁时解除事件监听
beforeDestroy(){
window.removeEventListener('online', this.updateOnlineStatus);
window.removeEventListener('offline', this.updateOnlineStatus);
},
完整测试代码如下:
<template>
<div>
<div class="tab">
<div class="hd">
<span v-bind:class="{cur:lanmu=='xinwen'}" v-on:click="change('xinwen')">新闻</span>
<span v-bind:class="{cur:lanmu=='tupian'}" v-on:click="change('tupian')">图片</span>
<span v-bind:class="{cur:lanmu=='junshi'}" v-on:click="change('junshi')">军事</span>
</div>
<div class="bd">
<div class="xinwen">{{lanmu}}</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
lanmu:"xinwen",
onLine: navigator.onLine,
}
},
methods:{
change:function(str){
this.lanmu = str;
},
updateOnlineStatus(e) {
const { type } = e;
this.onLine = type === 'online';
console.log("网络由异常")
},
},
mounted(){
window.addEventListener('online', this.updateOnlineStatus);// 网络由异常到正常时触发
window.addEventListener('offline', this.updateOnlineStatus);// 网络由正常常到异常时触发
}
}
</script>
<style>
.tab{
width: 360px;
height: 260px;
border:1px solid #000;
margin:100px auto;
}
.tab .hd{overflow: hidden;}
.tab .hd span{
float: left;
width: 120px;
height: 40px;
line-height: 40px;
background-color:#ccc;
text-align: center;
}
.tab .hd span.cur{
background-color: orange;
}
</style>
二、另外也可以采用H5的API拓展plusready来实现
<!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>
官方文档请参阅下述网址:
http://www.html5plus.org/doc/zh_cn/events.html
更多推荐
所有评论(0)