關於 ElementUI 通知組件 notification 重疊問題的解決方案


轉載鏈接:https://blog.csdn.net/csdn_yudong/article/details/101271214

ElementUI 通知組件(notification) 多個時會重疊問題的解決方案
問題場景
問題分析
解決方案
方案一 Promise
方案二 setTimeout
解決后效果
最后 - 示例
問題場景
使用 ElementUI 時,當你在一次觸發事件中,調用了兩次或更多的 相同位置 的 $notify 時,這時候,彈出的通知框會重疊。
比如:

doNotify() {
this.$notify({
title: '我的通知',
message: '右下角彈出的消息',
position: 'bottom-right'
})
this.$notify({
title: '我的通知',
message: '右上角彈出的消息',
position: 'bottom-right'
})
},
1
2
3
4
5
6
7
8
9
10
11
12
或者

doNotify() {
for(let i=0; i<3; i++) {
this.$notify({
title: '我的通知呀',
message: '右下角彈出的消息',
position: 'bottom-right'
})
}
}
1
2
3
4
5
6
7
8
9
觸發這個 doNotify 方法,看到的彈窗是重疊的:


問題分析
每一個通知組件在顯示之前需要計算它應該顯示的位置,他需要知道它前面的 通知實例 有多少個,然后進一步計算它自己應該顯示的位置。(它需要計算前一個通知組件的高度,然后再加上每個通知組件之間的間距 16px)

但是就像 Vue 官網里面 所說的:Vue 在更新 DOM 時是 異步 執行的。只要偵聽到數據變化,Vue 將開啟一個隊列,並緩沖在同一事件循環中發生的所有數據變更。然后,在下一個的事件循環“tick”中,Vue 刷新隊列並執行實際 (已去重的) 工作。

所以,在一個事件中,它不是立馬生效的,它會本次事件隊列完成后生效。

解決方案
Vue 在內部對異步隊列嘗試使用原生的 Promise.then、MutationObserver 和 setImmediate,如果執行環境不支持,則會采用 setTimeout(fn, 0) 代替。

You can use promise and setTimeout to solution

方案一 Promise
data() {
return {
notifyPromise: Promise.resolve()
}
},
methods: {
doNotify1() {
for(let i=0; i<3; i++) {
this.notifyPromise = this.notifyPromise.then(() => {
this.$notify({
title: '我的通知',
message: '右下角彈出的消息',
position: 'bottom-right'
})
})
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
方案二 setTimeout
data() {
return {
timer: null
}
},
methods: {
doNotify2() {
for(let i=0; i<3; i++) {
this.timer = window.setTimeout(() => {
this.$notify({
title: '你的彈窗',
message: '右下角彈出的消息',
position: 'bottom-right'
})
}, 0)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM