axios攔截器只彈一次el-message實現方法

場景說明

同一個賬號,兩個人使用,第二個人登錄成功後,當第一個人再次操作界面時,所有接口返回特定的102碼,這時前端知道這個賬號異地登錄了,現在要做的是讓前端給第一個人一個提示,告訴他他的賬號被別人使用了。

錯誤嘗試

第一反應是在axios攔截器內實現message彈出操作,實際情況是,第一個人觸發102碼的時候並不是每次只有一個接口請求,可能會有好幾個axios同時請求得到102碼,這個時候就會出現下面的場景:

在這裏插入圖片描述

錯誤代碼(簡寫)

import axios from 'axios'
import {Message} from 'element-ui'
const http = axios.create({
	timeout: 1000 * 60 * 2,
	withCredentials: true
})
// 當爲post請求時設置其Content-Type爲application/x-www-form-urlencoded
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 響應攔截
http.interceptors.response.use(res => {
	if (res.data.code === 102) {
		Message({
			message: '當前賬號已經在其他客戶端登錄',
			type: 'warning',
		})
		// 這裏執行清除token和跳轉到登錄頁等操作)

解決辦法

如何解決彈窗多次彈出的問題呢?實際情況下我們只希望它彈一次!

新建一個messageOnce.js文件,如下:

import {Message} from 'element-ui'
// 私有屬性,只在當前文件可用
const showMessage = Symbol('showMessage')
export default class domMessage {
	success (options, single = true) {
		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)
	}
	[showMessage] (type, options, single) {
		if (single) {
			// 關鍵代碼,判斷當前頁是否有el-message標籤,如果沒有則執行彈窗操作
			if (document.getElementsByClassName('el-message').length === 0) {
				Message[type](options)
			}
		} else {
			Message[type](options)
		}
	}
}

在處理響應攔截的文件中引入messageOnce.js,如下:

import axios from 'axios'
import domMessage from './messageOnce'

// new 對象實例
const messageOnce = new domMessage()
const http = axios.create({
	timeout: 1000 * 60 * 2,
	withCredentials: true
})
// 當爲post請求時設置其Content-Type爲application/x-www-form-urlencoded
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 響應攔截
http.interceptors.response.use(res => {
	if (res.data.code === 102) {
		messageOnce.warning({
			message: '當前賬號已經在其他客戶端登錄',
			type: 'warning'
		})
		// 這裏執行清除token和跳轉到登錄頁等操作)

總結

一開始打算使用防抖函數來處理,發現沒法解決這個問題,後來向朋友請教,提供了這個思路給我,很受用。如果覺得文章不錯,點個贊再走吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章