解决ElementUi 2.16.x版本 notifycation通知框 onClose事件无法区分自动关闭还是手动关闭问题。
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                Element UI 2.16.x 版本的 Notification 组件的 onClose 事件本身不提供是否是自动关闭的信息。但是,你可以通过一些方法来解决这个问题。
一种方法是使用一个标志来跟踪通知是手动关闭还是自动关闭。例如,你可以在关闭之前设置一个标志,并在 onClose 事件中检查这个标志。
下面是一个简单的示例:
// 引入 Notification
import { Notification, MessageBox } from 'element-ui';
 
// 创建 Notification 实例
const notify = (message, duration = 3000) => {
  let timer = null;
  const close = () => {
    clearTimeout(timer);
    Notification.closeAll();
  };
 
  const manualClose = () => {
    clearTimeout(timer);
    // 手动关闭的逻辑
  };
 
  const instance = Notification({
    title: '通知',
    message,
    duration,
    onClose: close, // 统一关闭逻辑
  });
 
  // 如果手动设置 duration 为 0,则认为是手动关闭
  if (duration === 0) {
    MessageBox.confirm('确认关闭通知?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      manualClose();
    }).catch(() => {
      // 用户取消,重新开始计时
      timer = setTimeout(() => {
        instance.close();
      }, duration);
    });
  } else {
    timer = setTimeout(() => {
      manualClose();
    }, duration);
  }
 
  return instance;
};
 
// 使用 notify 函数发送通知
notify('这是一条自动关闭的通知', 3000);
notify('这是一条不会自动关闭的通知', 0);在这个示例中,我们创建了一个 notify 函数,它接收一个消息和一个持续时间。如果指定了持续时间,并且不是手动设置为0,则通知会在指定时间后自动关闭。如果设置为0,则会显示一个确认对话框,用户可以选择关闭通知。通过这种方式,我们可以在 onClose 事件中统一处理关闭逻辑,并且可以通过检查是否用户手动触发关闭来区分是自动关闭还是手动关闭。
评论已关闭