解决element-ui 的 Notification 重叠问题
生活随笔
收集整理的這篇文章主要介紹了
解决element-ui 的 Notification 重叠问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天在開發的時候,遇到一個問題:
場景:
有一個數組,我需要遍歷這個數組,把這個數組里的每一項使用element-ui的Notification組件渲染在頁面右下角。
這還不簡單,arr.forEach()搞定啊!!!
tipsArr.forEach((item: string) => {this.$notify({title: item,message: '',position: 'bottom-right',type: 'warning',duration: 0,offset: 10}); })但是似乎沒我想得那么順利,因為代碼寫出來之后,頁面展示是這樣的,每一條信息都重疊到一起了,和官網展示的效果不太一樣啊???
我的提示信息都重疊到了一塊,關掉一條之后,才能看到下一條的內容,這不是我想要的效果哇!!!我希望它可以像官網展示的那樣,平鋪下來。
原因分析:
之后,通過查看了notify的源碼,找到了原因:
let verticalOffset = options.offset || 0; instances.filter(item => item.position === position).forEach(item => {verticalOffset += item.$el.offsetHeight + 16; }); verticalOffset += 16; instance.verticalOffset = verticalOffset;每一個Notification通知組件在顯示之前需要計算它應該顯示的位置,他需要知道它前面的 Notification 通知實例有多少個,然后進一步計算它自己應該顯示的位置,每次計算間距時,會取當前元素的高度:item.$el.offsetHeight ,但是因為vue的異步更新隊列有緩沖機制,第一次個通知渲染時,并沒有更新dom,導致取到的高度為0,所有第二個通知只是上移了默認的offset 16px,并沒有加上第一個通知的高度,之后的每一個通知都是只增加了16px的間距,最終渲染出來的通知組件,就是重疊在一起的。
解決方式:
方法一:使用nextTick方法
但這個方法有一定的局限性,就是你已知要渲染的通知信息只有少數幾條,或者已知數組的長度,數組的length值不是很長。
//已知 tipsArr的length值為2this.$notify({title: tipsArr[0],message: '',position: 'bottom-right',type: 'warning',duration: 0,offset: 10});this.$nextTick(() => {this.$notify({title: tipsArr[1],message: '',position: 'bottom-right',type: 'warning',duration: 0,offset: 10});})方法二:使用setTimeout
data() {return {timer: null} },tipsArr.forEach((item: string) => {this.timer = setTimeout(() => {this.$notify({title: item,message: '',position: 'bottom-right',type: 'warning',duration: 0,offset: 10});}, 0)this.$once('hook:beforeDestroy', () => {this.timer && clearTimeout(this.timer)this.timer = null}) })方式三:使用Promise
data() {return {notifyPromise: Promise.resolve()} }tipsArr.forEach((item: string) => {this.notifyPromise = this.notifyPromise.then(() => {this.$notify({title: item,message: '',position: 'bottom-right',type: 'warning',duration: 0,offset: 10});}) })解決后的效果:
總結
以上是生活随笔為你收集整理的解决element-ui 的 Notification 重叠问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米盒子1s搭建web服务器
- 下一篇: XML学习笔记——XSL