場景說明:
用戶登錄后放置一段時間,或者在別處被使用捂襟,當(dāng)該用戶再次訪問系統(tǒng)某頁面咬腕,可能同時請求X個接口,此時接口報401或102等狀態(tài)碼葬荷,頁面拋出錯誤涨共。因為同時調(diào)用了多個接口纽帖,頁面一次拋出好幾個彈窗。
image.png
錯誤代碼
import axios from 'axios'
import {Message} from 'element-ui'
const http = axios.create({
timeout: 1000 * 60 * 2,
withCredentials: true
})
// 當(dāng)為post請求時設(shè)置其Content-Type為application/x-www-form-urlencoded
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 響應(yīng)攔截
http.interceptors.response.use(res => {
if (res.data.code === 102) {
Message({
message: '當(dāng)前賬號已經(jīng)在其他客戶端登錄',
type: 'warning',
})
// ... 這里執(zhí)行清除token和跳轉(zhuǎn)到登錄頁等操作
}
)
解決辦法1: 創(chuàng)建 messageOnce.js
// import {Message} from 'element-ui'
import { MessageBox } from "element-ui";
// 私有屬性举反,只在當(dāng)前文件可用
const showMessage = Symbol('showMessage')
export default class domMessage {
success (options, single = true) { // Message方法
this[showMessage]('success', options, single)
}
warning(options, single = true) {
this[showMessage]('warning', options, single)
}
info(options, single = true) {
this[showMessage]('info', options, single)
}
error(options, single = true) {
this[showMessage]('error', options, single)
}
alert(options, single = true){
this[showMessage]('error', options, single)
}
[showMessage] (type, options, single) {
if (single) {
// 關(guān)鍵代碼懊直,判斷當(dāng)前頁是否有el-message標(biāo)簽,如果沒有則執(zhí)行彈窗操作
if (document.getElementsByClassName('el-message-box').length === 0 || document.getElementsByClassName('el-message-box__wrapper')[0].style.display=="none" ) {
MessageBox(options)
}
} else {
MessageBox(options)
}
}
}
使用 messageOnce方法
import Vue from "vue";
import axios from "axios";
import router from "@/router";
import domMessage from './messageOnce' // 引入方法
const messageOnce = new domMessage()
// 添加響應(yīng)攔截器
axios.interceptors.response.use(
(response) => {
const data = response.data;
if (data.code == 401) {
messageOnce.alert({
message: '登錄信息不存在或已過期',
title:'溫馨提示',
confirmButtonText: '確定',
showClose:false,
type: 'warning',
callback: () => {
sessionStorage.clear()
router.push(`/login`);
}
})
return data;
} else if (data.status == 500) {
messageBox({
title: "",
type: "warning-login",
content: data.message,
isSetTimeout: false,
});
return data;
} else {
return data;
}
},
(error) => {
var data = error.response.data
return Promise.reject(error);
}
)
解決辦法2
另一種思路是火鼻,在vueX中設(shè)置一個變量保存 過期標(biāo)識 lateFlag
其他形式保存也行室囊,自行發(fā)揮~~~
例如
if (err.status === 401 ) {
// 重新登陸
if (lateFlag== 0) {
lateFlag++
MessageBox.confirm('很抱歉,登錄已過期魁索,請重新登錄', {
confirmButtonText: '重新登錄',
showCancelButton: false,
type: 'warning'
}).then(() => {
db.remove('router')
db.remove('loginToken')
lateFlag= 0
router.push({ path: '/login' });
}).catch(()=>{
aaa = 0
// 確認(rèn)框點了取消后 標(biāo)識要復(fù)原 不然點了取消后再操作無法彈出登錄超時提示
});
}
return Promise.reject(error);
}