vue 根據接口返回的狀態碼判斷用戶登錄狀態並跳轉登錄頁,登錄后回到上一個頁面(http攔截器)


背景:后台接口返回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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM