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'
},() => {
	// 关闭时的回调
});
相关推荐
Ariel_jhy4 分钟前
fetch和axios的区别
前端
不想说话的麋鹿7 分钟前
《NestJS 实战:RBAC 系统管理模块开发 (一)》
前端·node.js·全栈
前端小同学10 分钟前
【硬核开源mcp-chrome】一个chrome插件,能让任意chatbot接管你的chrome浏览器
前端·人工智能
Uyker20 分钟前
解读Qwin
前端
月忆3641 小时前
等待组(waitgroup)
前端·爬虫·python
令狐寻欢1 小时前
HTML中 的 meta 标签常用属性及其作用
前端·html
SynthWriter1 小时前
Trae 帮我生成了一个贪吃蛇的游戏,好玩儿
前端
超级土豆粉1 小时前
JavaScript 标签加载
开发语言·javascript·ecmascript
用户21411832636021 小时前
dify案例分享-Dify+RSS 聚合 8 大平台实时热点,新闻获取效率飙升 300%
前端
百锦再1 小时前
Razor编程中@Html的方法使用大全
前端·html