返回

终于解决了element ui循环中this.$alert只显示最后一个的问题

前端

大家在element-ui中使用this.alert时,如果是在循环中使用,可能会遇到这样一个问题:this.alert消息提示只会显示最后一个。

```
this.$alert('内容', '标题', {
  confirmButtonText: '确定',
  callback: action => {
    this.$message({
      type: 'success',
      message: 'action: ' + action
    });
  }
});
```

上述代码中,this.$alert被放置在一个循环中,如果循环体中有10个元素,那么最终只 会弹出1this.$alert消息提示,并且显示的内容是最后一个元素的内容。

原因

出现这种情况的原因是,element-ui中的this.$alert是一个全局方法,它只会显示最后一个调 用的this.$alert消息提示。因此,当我们在循环中多次调用this.$alert时,只有最后一次调用的this.$alert消息提示会被显示。

解决办法

为了解决这个问题,我们可以使用setTimeout函数来延迟执行this.$alert方法。这样,每个this.$alert方法都会在不同的时间点执行,从而避免了只显示最后一个this.$alert消息提示的问题。

```
setTimeout(() => {
  this.$alert('内容', '标题', {
    confirmButtonText: '确定',
    callback: action => {
      this.$message({
        type: 'success',
        message: 'action: ' + action
      });
    }
  });
}, 100);
```

在这个例子中,我们使用了setTimeout函数将this.$alert方法的执行延迟了100毫秒。这样,每个this.$alert方法都会在100毫秒后执行,从而避免了只显示最后一个this.$alert消息提示的问题。

需要注意的是,setTimeout函数的延迟时间不能太短,否则可能会导致this.$alert消息提示闪烁。一般来说,延迟时间设置为100毫秒到200毫秒比较合适。