el-message 同时弹出多个【改写el-message】

时间:2024-11-09 07:56:15

因为服务断开了 但是拦截器里对每个失败的接口都做了message弹出,因此改写el-message逻辑,仅展示一个同等类型的message窗体 

1. 新建 @/utils/rewriteElMessage.js

/**
 * @Event 解决 el-message 同类型重复打开的问题
 * @description:
 * @author: mhf
 * @time: 2024-11-06 15:30:56
 **/
import {Message} from "element-ui";

const typeArr = ['success', 'warning', 'info', 'error'];

class NewMessage {
  static showMessage(type, options, single) {
    if (single && document.getElementsByClassName(`el-message--${type}`).length > 0) {
      return;
    }
    Message[type](options);
  }
}

typeArr.forEach(type => {
  NewMessage[type] = function (options, single = true) {
    this.showMessage(type, options, single);
  };
});

export default NewMessage;

2. main.js

import Vue from "vue";
import NewMessage from "@/utils/rewriteElMessage";
Vue.prototype.$message = NewMessage;

3. 使用

Vue中还是和之前一样 this.$message.success({}, true)

3.1拦截器js中使用

import NewMessage from "@/utils/rewriteElMessage";

    const errorCodeArr = [411, 412, 413, 415, 416];

    if (error.response) {
      NewMessage.error({
        message: error.response.data.message || error.response.data.error,
        duration: 5 * 1000
      });

      if (errorCodeArr.includes(Number(error.response.data.code))) {
        if (!isRelogin.show) {
          isRelogin.show = true;
          MessageBox.confirm(
            "登录状态已过期,您可以继续留在该页面,或者重新登录",
            "系统提示",
            {
              showCancelButton: false,
              confirmButtonText: "重新登录",
              cancelButtonText: "取消",
              type: "warning"
            }
          )
            .then(() => {
              isRelogin.show = false;
              store
                .dispatch("LogOut")
                .then(() => {
                  location.href = "/index";
                })
                .catch(() => {
                  location.href = "/index";
                });
            })
            .catch(() => {
              isRelogin.show = false;
            });
        }
      }
    } 

4. 如果不想区分message类型,即所有类型只展示一次

将rewriteElMessage.js改成如下即可

static showMessage(type, options, single) {
    // if (single && document.getElementsByClassName(`el-message--${type}`).length > 0) {
    if (single && document.getElementsByClassName(`el-message`).length > 0) {
      return;
    }
    Message[type](options);
  }