前言

因为业务须要,须要在封装的弹窗组件中引入定时器实现倒计时成果,然而如果同时触发两个弹窗,就会导致计时器bug,前一个弹窗的定时器没有被革除,倒计时就会错乱,此时想到的解决办法就是采纳队列模式,将每一个须要的弹窗存到队列中,顺次的将弹窗展现进去,同时革除定时器

什么是队列

队列(Queue) 是先进先出(FIFO, First-In-First-Out)的线性表。在具体利用中通常用链表或者数组来实现。队列只容许在尾部进行插入操作(入队 enqueue),在头部进行删除操作(出队 dequeue)。队列的操作形式和堆栈相似,惟一的区别在于队列只容许新数据在后端进行增加。

JavaScript实现队列的成果

function ArrayQueue(){      var arr = [];          //入队操作      this.push = function(element){          arr.push(element);          return true;      }          //出队操作      this.pop = function(){          return arr.shift();      }          //获取队首      this.getFront = function(){          return arr[0];      }          //获取队尾      this.getRear = function(){          return arr[arr.length - 1]      }          //清空队列      this.clear = function(){          arr = [];      }          //获取队长      this.size = function(){          return length;      }  }

和vue封装的弹窗组件应用

首先要配合组件封装队列要进行批改

class Queue {  dataStore = []  constructor(){    this.dataStore=[]  }  enqueue(e) {    this.dataStore.push(e)    console.warn('入队',this.dataStore);  }  dequeue() {    this.dataStore.shift()    console.warn('出队',this.dataStore);  }  front() {    console.log(this.dataStore,'front')    return this.dataStore[0]()  }  select(){    return this.dataStore[0]  }  back() {    return this.dataStore[this.dataStore.length - 1]  }  isEmpty() {    if (this.dataStore.length == 0) {      return true    }    return false  }  toString() {    return this.dataStore.join(',')  }}export default Queue

在弹出第一个队列的时候须要自执行。
在你的封装组件的函数中引入这个队列,同时实例化这个队列,写入两个办法.

const pushDialog = (eventName) => {  if (queue.isEmpty()) {    queue.enqueue(eventName);    openDialog();  } else {    queue.enqueue(eventName);  }}const openDialog = () => {  // 关上弹窗  queue.front();}

在装置的办法中将每一个弹窗退出队列中

须要留神的是,每个弹窗是要被销毁的,不然会导致办法反复。

举例在确认办法和定时器后怎么出队列和清空定时器