三种弹窗方式

Vant 提供三种常用的反馈组件,根据使用场景选择:

组件用途使用方式
Dialog确认操作(如删除、退出)函数式调用
Toast轻提示(如"保存成功")函数式调用
Notify顶部横幅通知函数式调用

三者都支持函数式调用(无需在模板里写组件),非常方便。

Dialog 确认弹窗

import { showDialog, showConfirmDialog } from "vant";

// 基础 Dialog
showDialog({
  title: "提示",
  message: "确定要执行此操作吗?",
}).then(() => {
  console.log("点击了确认");
}).catch(() => {
  console.log("点击了取消");
});

// 确认弹窗(显式双按钮)
showConfirmDialog({
  title: "删除确认",
  message: "删除后无法恢复,确定继续吗?",
  confirmButtonText: "删除",
  confirmButtonColor: "#ee0a24",
  cancelButtonText: "再想想",
})
  .then(() => console.log("用户确认"))
  .catch(() => console.log("用户取消"));

// 只显示确认按钮(Alert)
showDialog({
  title: "温馨提示",
  message: "您的账号已在其他设备登录",
  showCancelButton: false,
  confirmButtonText: "我知道了",
});

Toast 轻提示

import { showToast, showSuccessToast, showFailToast, showLoadingToast, closeToast } from "vant";

// 基础 Toast
showToast("操作成功");

// 带图标
showSuccessToast("保存成功");
showFailToast("网络错误");

// Loading Toast(手动关闭)
showLoadingToast({
  message: "加载中...",
  forbidClick: true, // 禁止点击穿透
  duration: 0,      // 不自动关闭
});
// 完成后手动关闭
closeToast();

最佳实践:Loading Toast 设置 duration: 0 手动关闭,防止接口未完成时提示消失。

实战:删除确认完整流程

import { showConfirmDialog, showToast, showLoadingToast, closeToast } from "vant";

const handleDelete = async (id) => {
  try {
    // 1. 弹出确认框
    await showConfirmDialog({
      title: "删除确认",
      message: "确定删除这条记录吗?",
      confirmButtonText: "删除",
      confirmButtonColor: "#ee0a24",
    });

    // 2. 用户确认后,显示 Loading
    showLoadingToast({ message: "删除中...", duration: 0 });

    // 3. 执行删除接口
    await api.deleteItem(id);

    // 4. 关闭 Loading,显示成功提示
    closeToast();
    showToast("删除成功");

    // 5. 刷新列表
    refreshList();
  } catch (e) {
    closeToast();
    if (e !== "cancel") {
      showToast("删除失败,请重试");
    }
  }
};

Notify 顶部通知

import { showNotify, closeNotify } from "vant";

showNotify({ type: "primary", message: "这是一条消息" });
showNotify({ type: "success", message: "操作成功" });
showNotify({ type: "danger", message: "网络异常" });
showNotify({ type: "warning", message: "注意" });

函数式 API 汇总

API返回值说明
showDialog(options)Promise通用弹窗
showConfirmDialog(options)Promise确认弹窗
showToast(message/options)void轻提示
showSuccessToast(message)void成功提示
showFailToast(message)void失败提示
showLoadingToast(options)void加载提示
closeToast()void关闭 Toast
showNotify(options)void顶部通知
closeNotify()void关闭通知