vue+element项目中页面多个接口异常,只提示一次异常信息

本文介绍了如何使用Element-UI的Message组件实现页面接口调用异常时的统一提示,避免因多个接口错误导致的多次弹窗,提高用户体验。通过创建私有属性和在响应拦截器中调用,确保每个错误仅显示一次警告消息。
摘要由CSDN通过智能技术生成

有时候一个页面会同时调多个接口,但是多个接口异常,需要做提示,那么提示的时候会弹出很多的提示信息,这无疑让体验感降低很多。  所以针对这种情况,我们配合element UI统一做一个异常状态的处理,只能显示一次提示的功能,后续代码调接口的时候

也可以省略去写异常状态下的逻辑了。
首先新建一个文件 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)
        }
    }
}

第二步,需要在你的响应拦截器(interceptors.response.use)的页面去引入刚才的文件,我取名为domMessage,引入:import domMessage from './messageOnce'
第三步,new 对象实例 const messageOnce = new domMessage()
第四步,在响应拦截器中去写

if (response.data.code && JSON.parse(response.data.code) == 500) {
      messageOnce.warning({
        message: '系统异常'+response.data.msg,
        type: 'warning'
      })
}

然后尝试就行了。

  • 13
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值