Element 通知组件 Notification 支持同类型的提示信息只弹出一次!!!

Element 使用闭坑指南

当我们在使用 Element Notification 通知组件的时候,由于该组件不是通过实例化来创建的,当有事件触发通知时我们就无法控制在同一个页面相同的消息只弹出一次,我们必须使用其它的手段来实现。能否通过一个标识来记录当前页面已经触发通知,我们根据这个标识来判断是否再次弹出相同的提示信息。

首先我们通过插件的方法,对 Notification 组件做个简单的封装,将判断逻辑整合进去。

import { Notification } from 'element-ui'

const $notify = options => {
  return Notification({
    ...options,
    duration: 0
  })
}

['success', 'warning', 'info', 'error'].forEach(type => {
  $notify[type] = options => {
    if (typeof options === 'string') {
      options = {
        message: options,
        type: type,
        title: '提示',
        duration: 0
      }
    } else {
      options = Object.assign({
        title: '提示',
        type: type,
        duration: 0
      }, options)
    }
    return Notification(options)
  }
})

Notification.install = function (Vue) {
  Vue.prototype.$notify = $notify
  Vue.prototype.$notify.close = Notification.close
}

export default Notification

封装好的插件我们使用在 main 里面导入并使用

import Notify from '@/plugins/notify'
// ...
Vue.use(Notify)

调用 this.notify() 参数可以直接是提示内容的字符串,也可以是配置对象

我们在 util 里封装三个工具函数,来分别从浏览器本地 Storage 缓存处理和判断事件标识

export function setNotifyFlag(eventKey) {
  return Vue.ls.set(eventKey, true, 60 * 60 * 1000)
}

export function removeNotifyFlag(eventKey) {
  return Vue.ls.set(eventKey, false)
}

export function checkNotifyFlag(eventKey) {
  return Vue.ls.get(eventKey)
}

然后在 Notification 事件回调方法里来增加判断,当本地缓存中相关通知事件的标识为空或者为 false 时,触发该通知的时候就调用 setNotifyFlag 来在本地缓存中插入标识。在人为关闭通知的时候来移除标识。

if (options.eventKey) {
  options.onClose = () => {
    removeNotifyFlag(options.eventKey)
  }
  if (!checkNotifyFlag(options.eventKey)) {
    setNotifyFlag(options.eventKey)
    return Notification(options)
  }
  return false
} else {
  return Notification(options)
}

这个方案也有个弊端,当用户离开页面,没有手动去关闭通知的话,就无法将缓存中的对应事件的值重置为 false,下次再进来就无法触发这个通知了。所以我们根据情况去设置这个缓存时间。或者下次想到什么更好的方案,再来更新此篇。

评论

还没有评论...留下你的评论!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Sidebar