背景:后台接口返回code==501表示用户是未登陆状态,须要登陆才可访问;vue
经过http拦截作路由跳转ios
第一步:src目录下新建http.js文件,内容以下:element-ui
import Axios from 'axios' import { Loading, Message, MessageBox } from 'element-ui' // 超时时间 Axios.defaults.timeout = 5000 // http请求拦截器 var loadinginstace Axios.interceptors.request.use(config => { // element ui Loading方法 loadinginstace = Loading.service({ fullscreen: true }) return config }, error => { loadinginstace.close(); Message.error({ message: '网络不给力,请稍后再试' }) return Promise.reject(error) }) // http响应拦截器 Axios.interceptors.response.use(data => { // 响应成功关闭loading loadinginstace.close(); const code = data.data.code; if(code == 501) { //未登陆 MessageBox.alert('请先登陆', '提示', { confirmButtonText: '肯定', callback: action => { router.replace({ name: 'login', query: {redirect: router.currentRoute.fullPath} //登陆后再跳回此页面时要作的配置 }) } }); } return data }, error => { loadinginstace.close(); Message.error({ message: '网络不给力,请稍后再试' }) return Promise.reject(error) })
2.从main.js中引入axios
import './http.js'
3.登陆页设置login.vueapi
if(this.$route.query.redirect){ this.$router.push({path: decodeURIComponent(this.$route.query.redirect)}) //跳转到原页面 }else{ this.$router.push({name: 'userIndex', query: {id: 0}});//正常登陆流程进入的页面 }
2019-04-14更新:cookie
tip1: 平台右上角须要显示用户名,后台在登陆时返回了用户名称信息,将他放在cookie中,在头部组件中调用cookie获取用户名便可。网络
tip2: 刚开始把http.js的内容直接放到了main.js中,会出现如下问题:ui
每次页面刷新时,地址少个apithis