Skip to content

全局服务 useUi

useUi() 返回一个全局反馈服务单例,可在页面内任意位置命令式唤起 toast / confirm / tips / loading,无需层层传递组件 ref。

服务按当前页面路径注册实例:jz-page(或独立的 jz-ui 组件)挂载时会调用 createUi() 写入当前页面的反馈能力,因此每个页面各自持有独立实例,页面间互不串扰。

使用前提

页面需挂载反馈服务节点,二选一:

  1. 使用 <jz-page> 作为根节点(推荐,已内置 jz-ui);
  2. 或在页面中手动放置 <jz-ui></jz-ui>

若当前页面未挂载,useUi() 的调用会被静默忽略(内部实例为 null)。

API

uts
import { useUi } from "@/uni_modules/jzfw-ui";
const ui = useUi();
方法签名说明
showToast(options: JzToastOptions) => void命令式弹出轻提示
showConfirm(options: JzConfirmOptions) => void命令式弹出确认框(含确认 / 取消)
showTips(message: string, callback: (action: JzConfirmAction) => void) => void仅含确定按钮的提示框
showLoading(title?: string, mask?: boolean) => void显示系统加载态,title 为空时用内置文案「加载中」
hideLoading() => void隐藏系统加载态

showToast

uts
import { useUi, t } from "@/uni_modules/jzfw-ui";
import type { JzToastOptions } from "@/uni_modules/jzfw-ui/types/index.uts";

const ui = useUi();

ui.showToast({ message: t("操作成功") } as JzToastOptions);

ui.showToast({
  type: "success",        // success | warn | error | question | disabled | stop
  message: "已保存",
  position: "center",     // top | center | bottom
  duration: 2000,         // 0 表示不自动关闭
  clear: true             // 清除已存在的吐司
} as JzToastOptions);

JzToastOptions 字段:

字段类型说明
messagestring文本内容(必填)
type?JzToastType语义类型,映射内置图标
icon?string自定义图标,优先于 type
image?string图片地址
position?JzToastPosition显示位置 top/center/bottom
duration?number显示时长(ms),0 不自动关闭
clear?boolean是否清除已存在的吐司

showConfirm

uts
import type { JzConfirmOptions, JzConfirmAction } from "@/uni_modules/jzfw-ui/types/index.uts";

ui.showConfirm({
  title: t("提示"),
  message: "确定删除该条记录吗?",
  confirmText: t("确定"),
  cancelText: t("取消"),
  callback: (action: JzConfirmAction) => {
    if (action == "confirm") {
      // 执行删除
    }
  }
} as JzConfirmOptions);

JzConfirmOptions 字段:

字段类型说明
titlestring标题(必填)
messagestring内容(必填)
callback?(action: JzConfirmAction) => void操作回调,action 为 confirm/cancel/close
beforeClose?(action, event: JzConfirmBeforeCloseEvent) => void关闭前钩子,可做异步校验
confirmText? / showConfirm?string / boolean确认按钮文案 / 是否显示
cancelText? / showCancel?string / boolean取消按钮文案 / 是否显示
duration?number自动关闭时长(ms),0 不自动关闭

beforeCloseevent 提供 close()showLoading()hideLoading(),用于点击确认后先做异步处理再关闭:

uts
ui.showConfirm({
  title: "提交",
  message: "确认提交表单?",
  beforeClose: (action, event) => {
    if (action == "confirm") {
      event.showLoading();
      // 异步请求...
      // 完成后:
      event.hideLoading();
      event.close();
    } else {
      event.close();
    }
  }
} as JzConfirmOptions);

showTips

仅含确定按钮的提示框,内部用 jz-confirmshowCancel: false,标题为「提示」)实现:

uts
ui.showTips("这是一条提示", (action) => {
  // action 通常为 "confirm"
});

showLoading / hideLoading

基于 uni.showLoadingtitle 为空时使用内置文案「加载中」(走多语言):

uts
ui.showLoading();            // 默认「加载中」,mask=true
ui.showLoading("提交中");     // 自定义文案
// ...异步结束
ui.hideLoading();

组件形式

上述能力由 jz-ui 组件挂载,它内部聚合了两个 jz-confirm(确认框 / 提示框)与一个 jz-toast。详见 反馈组件 · jz-ui

jzfw-ui 操作手册