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'
},() => {
	// 关闭时的回调
});
相关推荐
pan_junbiao3 小时前
Go 语言基本数据类型
java·前端·golang
Thanks_ks9 小时前
JavaScript 事件循环机制详解:同步任务、微任务与宏任务的执行顺序
javascript·promise·前端面试·async/await·事件循环·宏任务·微任务
ZhengEnCi11 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
kyriewen12 小时前
我给 61 个前端库排了两次名,最多差了 46 位
前端·javascript·程序员
亲亲小宝宝鸭12 小时前
Cesium启动:TLE数据是如何变成轨迹线的
前端·cesium
阿里云云原生12 小时前
对话即构建,在 AgentCore 构建 Agent 就是这么简单
前端·agent
夕水13 小时前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript
KevinWang_14 小时前
iOS 开发计划(五) - 做一个离线音乐播放器
javascript
狗头大军之江苏分军14 小时前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬14 小时前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust