背景:后台接口返回code==501表示用戶是未登錄狀態,需要登錄才可訪問;
通過http攔截做路由跳轉
第一步:src目錄下新建http.js文件,內容如下:
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中引入
import './http.js'
3.登錄頁設置login.vue
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更新:
tip1: 平台右上角需要顯示用戶名,后台在登錄時返回了用戶名稱信息,將他放在cookie中,在頭部組件中調用cookie獲取用戶名即可。
tip2: 剛開始把http.js的內容直接放到了main.js中,會出現以下問題:
每次頁面刷新時,地址少個api