优化前代码:
import { ElMessageBox } from 'element-plus';
ElMessageBox({
title: '系统提示',
message: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
beforeClose: (action, instance, done) => {
if (action === 'confirm') {
//确定按钮操作
.........
done()
} else {
//取消按钮操作
.........
done()
}
},
}).then((action) => {
}).catch(() => {
})
![](https://img-blog.csdnimg.cn/img_convert/c4a43003ad4cb2dd746bf91b80979711.png)
每次打开MessageBox时,“确定”按钮都是处于失焦状态的,需要鼠标点击下页面才能恢复聚焦状态
问题原因:MessageBox组件有一个autofocus属性,作用如下
![](https://img-blog.csdnimg.cn/img_convert/f8bad5e9fabb506239a5cc74f32e82d3.png)
该属性默认为true,即打开MessageBox时,MessageBox”夺取“了页面的聚焦状态,导致”确定“按钮失焦;
优化后代码:
import { ElMessageBox } from 'element-plus';
ElMessageBox({
title: '系统提示',
message: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消',
//将autofocus设为false,”确定”按钮即可自动获取焦点
autofocus: false,
type: 'warning',
beforeClose: (action, instance, done) => {
if (action === 'confirm') {
//确定按钮操作
.........
done()
} else {
//取消按钮操作
.........
done()
}
},
}).then((action) => {
}).catch(() => {
})
![](https://img-blog.csdnimg.cn/img_convert/4a2ec9bb2dcc6f36958697a3ffe516c1.png)