1、我们先来看看人家应用是怎么处理的
- 正常访问
- 断网时,会有个重新加载,当网络正常时,点击会回到原来的页面
下面说下思路吧 ,这里用的是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( res => res.status === 200 ? Promise.resolve(res)&store.commit('changeNetworkSuccess', true) : Promise.reject(res),
error => { const { response } = error; console.log(94,response) if (response) { errorHandle(response.status, response.data.message); return Promise.reject(response); } else { store.commit('changeNetworkSuccess', false); tip('网络异常!'); router.push({path:'refresh'}) } });
const errorHandle = (status, other) => { switch (status) { case 401: toLogin(); break; case 403: tip('登录过期,请重新登录'); localStorage.removeItem('token'); store.commit('loginSuccess', null); setTimeout(() => { toLogin(); }, 1000); break; case 404: tip('请求的资源不存在'); break;
default: console.log('其它错误',other); }}
|
最后更新时间: