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'
},() => {
	// 关闭时的回调
});
相关推荐
前端涂涂1 分钟前
JavaScript面试宝典
前端·javascript
卖报的小行家_6 分钟前
读《Vue.js设计与实现》第四章·响应系统的作用与实现
前端
七月丶8 分钟前
🚀 前端缓存踩坑指南:如何优雅地解决浏览器缓存问题?
前端
沉默王二9 分钟前
更快更强!字节满血版DeepSeek在IDEA中真的爽!
java·前端·程序员
掘金酱15 分钟前
👏 用idea传递无限可能!AI FOR CODE挑战赛「创意赛道」作品提交指南
前端·人工智能·trae
Hamm17 分钟前
咦,你的Git仓库贡献者里怎么有这么多大佬???
前端·git·github
潜龙在渊灬34 分钟前
前端 UI 框架发展史
javascript·vue.js·react.js
陈卓4101 小时前
Redis-限流方案
前端·redis·bootstrap
顾林海1 小时前
Flutter Dart 运算符全面解析
android·前端
七月丶1 小时前
🚀 现代 Web 开发:如何优雅地管理前端版本信息?
前端