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'
},() => {
	// 关闭时的回调
});
相关推荐
JosieBook8 分钟前
【web应用】基于Vue3和Spring Boot的课程管理前后端数据交互过程
前端·spring boot·交互
刘大猫.15 分钟前
npm ERR! cb() never called!
前端·npm·node.js·npm install·npmm err·never called
咔咔一顿操作19 分钟前
常见问题三
前端·javascript·vue.js·前端框架
前端程序媛Ying20 分钟前
点击按钮滚动到底功能vue的v-on:scroll运用
javascript
上单带刀不带妹20 分钟前
Web Worker:解锁浏览器多线程,提升前端性能与体验
前端·js·web worke
电商API大数据接口开发Cris36 分钟前
Node.js + TypeScript 开发健壮的淘宝商品 API SDK
前端·数据挖掘·api
还要啥名字39 分钟前
基于elpis下 DSL有感
前端
一只毛驴44 分钟前
谈谈浏览器的DOM事件-从0级到2级
前端·面试
用户8168694747251 小时前
封装ajax
前端
pengzhuofan1 小时前
Web开发系列-第13章 Vue3 + ElementPlus
前端·elementui·vue·web