发现问题
最近开发electron项目时,需要使用一个通知队列来显示通知,并且能够根据下标位置关闭对应位置的通知。同时,我们要删除指定位置下存在的通知实例以减少内存占用。
分析问题
- 根据elementui官网所示调用 Notification 或 this.$notify 会返回当前 Notification 的实例。如果需要手动关闭实例,可以调用它的 close 方法。
- 根据此网站描述,我们必须根据通知的ID来关闭通知。
由以上两个条件可知,我们需要能够访问通知队列的某一个通知,同时能够删除它,使他不占用内存,仅仅是对象是不够的,因此,我采用的是数组和对象结合的方法。
解决问题
- 创建两个数组,
notificationIdList
和notificationList
分别用来保存通知的Id和通知实例 - 假设我们要指定删除通知的位置是3,即
i = 3
- 添加通知实例:首先创建一个通知实例,定义一个临时对象
n
,对临时对象赋值:n[notify.id] = notify
,将这个临时对象n
添加到notificationList
数组中,将notify.id
添加到notificationIdList
数组中 - 删除通知实例:首先根据
i
,从notificationIdList
找到对应位置的notify.id
,并将其临时保存到notifyId
变量中,其次再通过i
,从notificationList
中找到对应位置的通知实例(item
),通过item['notifyId'].close()
的方式关闭该位置下的通知 - 最后根据
i
,使用数组的splice方法进行删除,达到目的。
代码展示
// 删除通知
deleteNotification(){
let i = 3
let m = 0
let notifyId = ''
this.notificationIdList.forEach(item => {
if(i === m){
// 找到对应项的通知id
notifyId = item
}
m ++
})
this.notificationIdList.splice(i, 1)
let j = 0
this.notificationList.forEach(item => {
if( i === j){
item[notifyId].close()
}
j ++
})
this.notificationList.splice(i, 1)
console.log(this.notificationList)
},
// 添加通知
addNotification(){
let notify = this.$notify.info({
title: '远程消息',
message: '111',
duration: 0
})
let n = {}
n[notify.id] = notify
this.notificationList.push(n)
this.notificationIdList.push(notify.id)
console.log(this.notificationList)
},
效果图展示
添加通知后
删除通知后