解决element组件 的 Notification 重叠问题

需求场景

有一个数组,我需要遍历这个数组,把这个数组里的每一项使用element组件的Notification组件渲染在页面右下角。想的很好 现实很残酷

他会好几个循环弹出的弹框会重叠在一块!!!!! 关掉一条之后,才能看到下一条的内容  我需要官网上给的效果 一条条滚动往上展示

网上搜索到的原因(源码)

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的间距,最终渲染出来的通知组件,就是重叠在一起的。


解决方法

1.使用nextTick方法

但这个方法有一定的局限性,就是你已知要渲染的通知信息只有少数几条,或者已知数组的长度,数组的length值不是很长。

import { ElNotification } from 'element-plus'
//已知 arrList的length值为2
 
 nextTick(() => {
         ElNotification({
                type: 'warning',
               title: arrList.value[0],
                message: '',
               position: 'bottom-right',
               offset: 10
         })
  });

 nextTick(() => {
         ElNotification({
                type: 'warning',
               title: arrList.value[1],
                message: '',
               position: 'bottom-right',
               offset: 10
         })
  });


 

2.使用setTimeout

import { ref, onBeforeUnmount } from 'vue';
import { ElNotification } from 'element-plus'
export default {
  setup() {
    const timer = ref(null);

    const tipsArr = ["Tip 1", "Tip 2", "Tip 3"]; // 你的提示数组

    tipsArr.forEach((item) => {
      timer.value = setTimeout(() => {
         ElNotification({
                   type: 'warning',
                  title: '警告',
                  message: item.msg,
                    position: 'bottom-right',
                   offset: 10
             })
      }, 0);

      // 在组件销毁前清除定时器
      onBeforeUnmount(() => {
        timer.value && clearTimeout(timer.value);
        timer.value = null;
      });
    });

    // 返回数据
    return {
      timer,
    };
  },
};

3.使用promise

    import { ElNotification } from 'element-plus'
const notifyPromise = ref(Promise.resolve())

  phaseValue.forEach((value, index, array) => {
        notifyPromise.value = notifyPromise.value.then(() => {
              ElNotification({
                   type: 'warning',
                  title: '警告',
                  message: value.msg,
                    position: 'bottom-right',
                   offset: 10
             })
       })
  })

最后的结果

猜你喜欢

转载自blog.csdn.net/m0_65607651/article/details/135393260