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

7,440次阅读
没有评论

共计 1522 个字符,预计需要花费 4 分钟才能阅读完成。

Element 使用闭坑指南

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

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,下次再进来就无法触发这个通知了。所以我们根据情况去设置这个缓存时间。或者下次想到什么更好的方案,再来更新此篇。

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于1970-01-01发表,共计1522字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)