uni.showModal 是 uni-app 中用于显示模态弹窗的 API,通常用于确认操作、提示信息或让用户做出选择。
基本用法
javascript
uni.showModal({
title: "提示",
content: "这是一个模态弹窗",
success: function (res) {
if (res.confirm) {
console.log("用户点击确定");
} else if (res.cancel) {
console.log("用户点击取消");
}
},
});
参数说明
| 参数 | 类型 | 默认值 | 必填 | 说明 |
|---|---|---|---|---|
title |
String | - | 否 | 提示的标题 |
content |
String | - | 是 | 提示的内容 |
showCancel |
Boolean | true | 否 | 是否显示取消按钮 |
cancelText |
String | '取消' | 否 | 取消按钮的文字 |
cancelColor |
String | '#000000' | 否 | 取消按钮的文字颜色 |
confirmText |
String | '确定' | 否 | 确定按钮的文字 |
confirmColor |
String | '#007aff' | 否 | 确定按钮的文字颜色 |
success |
Function | - | 否 | 接口调用成功的回调函数 |
fail |
Function | - | 否 | 接口调用失败的回调函数 |
complete |
Function | - | 否 | 接口调用结束的回调函数 |
success 返回参数说明
success 回调函数会收到一个对象参数,包含以下属性:
| 参数名 | 类型 | 说明 |
|---|---|---|
confirm |
Boolean | 为 true 时,表示用户点击了确定按钮 |
cancel |
Boolean | 为 true 时,表示用户点击了取消按钮 |
示例代码
基础用法
javascript
uni.showModal({
title: "提示",
content: "确定要删除该项吗?",
success: function (res) {
if (res.confirm) {
console.log("用户点击确定");
// 执行删除操作
} else if (res.cancel) {
console.log("用户点击取消");
}
},
});
自定义按钮文字
javascript
uni.showModal({
title: "操作确认",
content: "是否确认提交申请?",
confirmText: "确认提交",
cancelText: "暂不提交",
success: function (res) {
if (res.confirm) {
// 提交申请逻辑
} else if (res.cancel) {
// 取消操作
}
},
});
仅显示确定按钮
javascript
uni.showModal({
title: "系统提示",
content: "操作成功!",
showCancel: false,
confirmText: "知道了",
});
自定义按钮颜色
javascript
uni.showModal({
title: "重要提醒",
content: "此操作不可撤销,请谨慎操作!",
confirmColor: "#ff0000",
cancelColor: "#999999",
success: function (res) {
if (res.confirm) {
// 用户确认操作
}
},
});
注意事项
- 弹窗内容不宜过长,避免影响用户体验
- 在 iOS 平台,如果
showCancel设置为 false,则不会显示取消按钮 confirmColor和cancelColor颜色值需使用十六进制格式- 模态弹窗会中断用户操作流程,应谨慎使用
- 在微信小程序中,最多只能同时存在一个模态弹窗
完整示例
javascript
// 删除确认对话框
function deleteItem(itemId) {
uni.showModal({
title: "删除确认",
content: "确定要删除这条记录吗?此操作不可恢复!",
confirmColor: "#ff3333",
confirmText: "删除",
cancelText: "取消",
success: function (res) {
if (res.confirm) {
// 调用删除接口
deleteApi(itemId)
.then(() => {
uni.showToast({
title: "删除成功",
icon: "success",
});
// 刷新列表
refreshList();
})
.catch(() => {
uni.showToast({
title: "删除失败",
icon: "none",
});
});
} else if (res.cancel) {
console.log("用户取消删除");
}
},
});
}