1、我们先来看看人家应用是怎么处理的

  • 正常访问
    :height=
    :height="400px" width="200px"
  • 断网时,会有个重新加载,当网络正常时,点击会回到原来的页面
    :height=
    :height="400px" width="200px"

下面说下思路吧 ,这里用的是vue

1.新建refresh.vue断网页面,当断网时,我们跳转到这个页面。

2.监听接口,在vuex中新建一个networkSuccess参数,断网为false,联网为true

3.根据networkSuccess来判定跳不跳转到refresh.vue页面。

2、vuex store.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {
networkSuccess: true //是否断网
},
mutations: {
changeNetworkSuccess(state,val){ //改变状态
state.networkSuccess = val
}
},
actions: {

}
})

3、断网页面-refresh.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  <template>
<div class="refresh" v-if="!networkSuccess">
<h3>我断网了</h3>
<button @click="onRefresh()">点我刷新</button>
</div>
</template>
<script>
import {mapState } from 'vuex';
export default {
name: '',
data() {
return {}
},
methods: {
onRefresh(){
this.$router.go(-1)//返回之前点击的页面
},
},
computed:{
...mapState(['networkSuccess'])
},
}
</script>

4、利用axios的拦截器来判断是否断网

  • 响应拦截器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  import axios from 'axios';
import router from '../router';
import store from '@/store';
// 响应拦截器
instance.interceptors.response.use(
// 请求成功 --->成功的时候把NetworkSuccess置为true
res => res.status === 200 ? Promise.resolve(res)&store.commit('changeNetworkSuccess', true) : Promise.reject(res),
// 请求失败

error => {
const { response } = error;
console.log(94,response)
if (response) {
// 请求已发出,但是不在2xx的范围 errorHandle为解析错误码
errorHandle(response.status, response.data.message);
return Promise.reject(response);
} else {
// 处理断网的情况
// eg:请求超时或断网时,更新state的network状态
// network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
// 关于断网组件中的刷新重新获取数据,会在断网组件中说明
store.commit('changeNetworkSuccess', false);
tip('网络异常!');
router.push({path:'refresh'})
}
});

/**
* 请求失败后的错误统一处理
* @param {Number} status 请求失败的状态码
*/
const errorHandle = (status, other) => {
// 状态码判断
switch (status) {
// 401: 未登录状态,跳转登录页
case 401:
toLogin();
break;
// 403 token过期
// 清除token并跳转登录页
case 403:
tip('登录过期,请重新登录');
localStorage.removeItem('token');
store.commit('loginSuccess', null);
setTimeout(() => {
toLogin();
}, 1000);
break;
// 404请求不存在
case 404:
tip('请求的资源不存在');
break;
/*case 500:
store.commit('changeNetworkSuccess', false);
tip('网络异常!');
router.push({path:'refresh'})*/
default:
console.log('其它错误',other);
}}