Vue - 详细完美解决 ElementUI MessageBox “多次“ 弹框问题,让其无论执行多少次都只弹出来一次(常见于请求拦截器多次触发弹框,导致弹出来很多个)详细示例代码,保证完美解决!
在Vue中使用ElementUI的MessageBox时,可能会遇到“多次”弹出MessageBox的问题。这通常是因为MessageBox是异步的,而且每次调用MessageBox.confirm等方法时都会创建一个新的实例,导致多个实例堆积。
解决方案:
- 使用全局变量或Vuex状态来控制MessageBox的显示状态,确保同时只显示一个MessageBox。
- 封装一个自定义的MessageBox方法,在该方法内部管理显示状态,确保不会重叠显示。
以下是封装自定义MessageBox方法的示例代码:
// Vue 组件中
export default {
data() {
return {
// 用于控制MessageBox显示的标志
messageBoxVisible: false
};
},
methods: {
async showConfirmationBox(message) {
// 如果MessageBox已经显示,则不再显示
if (this.messageBoxVisible) return;
// 设置MessageBox显示状态为true
this.messageBoxVisible = true;
try {
// 显示MessageBox
const response = await this.$confirm(message, '确认', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
});
// 根据需要处理用户的选择
if (response === 'confirm') {
// 用户点击了确认
} else {
// 用户点击了取消
}
} catch (e) {
// 用户关闭了MessageBox
} finally {
// 无论用户如何选择,最后都将设置MessageBox显示状态为false
this.messageBoxVisible = false;
}
}
}
};
在上述代码中,我们通过messageBoxVisible
标志来控制是否显示MessageBox。如果MessageBox已经显示,我们不会再显示新的MessageBox。这样就可以防止用户看到多个MessageBox。当MessageBox关闭后,无论成功、取消或关闭,我们都将设置messageBoxVisible
为false
,以允许下一个MessageBox可以显示。
评论已关闭