elementUI提示、通知、弹框每次只出现一个

一、封装辅助函数

js 复制代码
/**
 * 防止重复弹出message、Notification、MessageBox弹框
 */

import { Message, Notification, MessageBox } from 'element-ui';

let currentMessage = null;
let currentMessageBox = null;
let currentNotification = null;

/*
 * 防止重复弹出Message
 * @param {Object} config - MessageBox默认的配置参数
 */

export function elMessage(options){
  if (currentMessage) {
    currentMessage.close();
  }
  currentMessage = Message(options);
}

['error', 'success', 'info', 'warning'].forEach((type) => {
  elMessage[type] = (options) => {
    if (typeof options === 'string') {
      options = {
        message: options,
      };
    }
    options.type = type;
    return elMessage(options);
  };
});

/*
 * 防止重复弹出MessageBox
 * @param {Object} config - MessageBox默认的配置参数
 * @param {function} callback 回调函数
 */

export function elMessageBox(config, closeBack) {
  if (currentMessageBox && currentMessageBox.close) {
    currentMessageBox.close();
  }
  currentMessageBox = MessageBox({
    ...config,
    callback() {
      if (closeBack) {
        closeBack();
      }
      currentMessageBox = null;
    },
  });
}

/*
 * 防止重复弹出Notification
 * @param {Object} config - Notification默认的配置参数
 * @param {function} callback 回调函数
 */

export function elNotification(config, closeBack) {
  // 关闭之前的Notification
  if (currentNotification && currentNotification.close) {
    currentNotification.close();
  }
  // 新创建一个Notification
  currentNotification = Notification({
    ...config,
    // 关闭后,执行回调函数,关闭后重置currentNotification为null
    onClose() {
      if (closeBack) {
        closeBack();
      }
      currentNotification = null;
    },
  });
}

二、全局引入

js 复制代码
import { elMessage,elMessageBox,elNotification } from '@/utils/el-hint';
// 国际化
import i18n from './lang/index';
// element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI, {
  size: 'medium',
  i18n: (key, value) => i18n.t(key, value)
});
// 一定要放在引入ElementUI,否则不生效
Vue.prototype.$message = elMessage; //设置全局
Vue.prototype.$elMessageBox = elMessageBox; //设置全局
Vue.prototype.$elNotification = elNotification; //设置全局

三、使用

js 复制代码
this.$message.success('1111');

this.$elMessageBox({
	title:'标题',
	message:'111',
	showClose:false,
},() => {
	// 关闭时的回调
});

this.$elNotification({
	title:'111',
	message:'222',
	type:'error'
},() => {
	// 关闭时的回调
});
相关推荐
灰小猿42 分钟前
Spring前后端分离项目时间格式转换问题全局配置解决
java·前端·后端·spring·spring cloud
im_AMBER1 小时前
React 16
前端·笔记·学习·react.js·前端框架
02苏_1 小时前
ES6模板字符串
前端·ecmascript·es6
excel1 小时前
⚙️ 一次性警告机制的实现:warnOnce 源码深度解析
前端
excel1 小时前
Vue SFC 样式编译核心机制详解:compileStyle 与 PostCSS 管线设计
前端
excel1 小时前
🧩 使用 Babel + MagicString 实现动态重写 export default 的通用方案
前端
excel1 小时前
Vue SFC 编译器主导出文件解析:模块组织与设计哲学
前端
excel1 小时前
深度解析:Vue SFC 模板编译器核心实现 (compileTemplate)
前端
excel1 小时前
Vue SFC 解析器源码深度解析:从结构设计到源码映射
前端
excel1 小时前
Vue SFC 编译全景总结:从源文件到运行时组件的完整链路
前端