解决:同时发起多个请求后,响应拦截后返回多个重复弹窗问题

我们在一个页面中也许会请求多条数据,如果出现token过期或返回异常错误的时候,使用拦截器拦截报错就会使message组件重复弹出。
下面我们将对这个问题进行一个简单处理:修改后只返回一个弹窗。
注:这里选用的是Element-UI中的 MessageNotify 组件(其他组件也类似)

创建src/utils/resetPopup.js

import Vue from 'vue';
/**重置message,防止重复点击重复弹出message弹框 */
let messageInstance = null;
const resetMessage = (options) => {
    //关闭上一个弹窗,继续下一个弹窗
    if (messageInstance) {
        messageInstance.close() //手动关闭实例,调用它的 close 方法,详细内容请参考Element-ui官方文档。
    }
    messageInstance = Vue.prototype.$message(options)
};
['error', 'success', 'info', 'warning'].forEach(type => {
    resetMessage[type] = options => {
        if (typeof options === 'string') {
            options = {
                message: options
            }
        }
        options.type = type
        return resetMessage(options)
    }
})
export const Message = resetMessage;
/**重置Notify,防止重复点击重复弹出Notify弹框 */
let notifyInstance = null;
const resetNotify = (options) => {
    //关闭上一个弹窗,继续下一个弹窗
    if (notifyInstance) {
        notifyInstance.close() //手动关闭实例,调用它的 close 方法,详细内容请参考Element-ui官方文档。
    }
    notifyInstance = Vue.prototype.$notify(options)
};
['error', 'success', 'info', 'warning'].forEach(type => {
    resetNotify[type] = options => {
        if (typeof options === 'string') {
            options = {
                title: options
            }
        }
        options.type = type
        return resetNotify(options)
    }
})
export const Notify = resetNotify;

使用方式

import { Message , Notify } from '@/utils/resetPopup' //重置弹窗
Message({
    message: response.data.msg,
    type: 'error',
    duration: 2000
})
Notify({
    title: response.data.msg,
    type: 'error',
    duration: 2000
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容