Skip to content

对话框

免费插件

此插件免费开源,采用 MIT 许可证。

概述

Dialog API 提供跨平台的原生警告对话框和 Toast/Snackbar 通知。

安装

shell
composer require nativephp/mobile-dialog

使用

警告对话框

php
use Native\Mobile\Facades\Dialog;
use Native\Mobile\Events\Alert\ButtonPressed;

// 简单警告
Dialog::alert('你好', '欢迎使用我们的应用!');

// 带自定义按钮的警告
Dialog::alert('确认', '你确定吗?', ['取消', '删除'])
    ->id('delete-confirm')
    ->show();

// 监听按钮点击
#[OnNative(ButtonPressed::class)]
public function handleButton($index, $label, $id = null)
{
    if ($id === 'delete-confirm' && $label === '删除') {
        $this->deleteItem();
    }
}
js
import { dialog, on, off, Events } from '#nativephp';

// 简单警告
await dialog.alert('你好', '欢迎使用我们的应用!');

// 带自定义按钮的警告
await dialog.alert('确认', '你确定吗?', ['取消', '删除'])
    .id('delete-confirm');

// 监听按钮点击
const handleButton = (payload) => {
    const { index, label, id } = payload;
    if (id === 'delete-confirm' && label === '删除') {
        deleteItem();
    }
};

on(Events.Alert.ButtonPressed, handleButton);

Toast 通知

php
use Native\Mobile\Facades\Dialog;

// 短时 toast(2 秒)
Dialog::toast('项目已保存!', 'short');

// 长时 toast(4 秒)- 默认
Dialog::toast('处理完成');
js
import { dialog } from '#nativephp';

// 短时 toast
dialog.toast('项目已保存!', 'short');

// 长时 toast(默认)
dialog.toast('处理完成');

配置方法

警告方法

id(string $id)

为警告设置唯一标识符。用于识别哪个警告触发了按钮点击。

php
Dialog::alert('标题', '消息', ['确定', '取消'])
    ->id('my-alert');

event(string $eventClass)

指定按钮点击时要分发的自定义事件类。

php
Dialog::alert('标题', '消息')
    ->event(MyCustomEvent::class);

remember()

将警告 ID 存储在会话中以便在事件处理器中检索。

php
Dialog::alert('标题', '消息')
    ->id('confirm-action')
    ->remember();

show()

显式显示警告对话框。

事件

ButtonPressed

当用户点击警告对话框中的按钮时触发。

Payload:

  • int $index - 按钮索引(从 0 开始)
  • string $label - 按钮标签文本
  • ?string $id - 警告 ID(如果设置了)
php
use Native\Mobile\Attributes\OnNative;
use Native\Mobile\Events\Alert\ButtonPressed;

#[OnNative(ButtonPressed::class)]
public function handleButton($index, $label, $id = null)
{
    match($label) {
        '删除' => $this->delete(),
        '取消' => null,
        default => null,
    };
}
js
import { on, off, Events } from '#nativephp';
import { onMounted, onUnmounted } from 'vue';

const handleButton = (payload) => {
    const { index, label, id } = payload;
    if (label === '删除') {
        deleteItem();
    }
};

onMounted(() => on(Events.Alert.ButtonPressed, handleButton));
onUnmounted(() => off(Events.Alert.ButtonPressed, handleButton));

平台行为

警告对话框

  • Android: 通过 NativeActionCoordinator 使用原生 AlertDialog
  • iOS: 使用 .alert 样式的原生 UIAlertController

Toast 通知

  • Android: Material Design Snackbar(位于底部导航栏上方)
  • iOS: 自定义 ToastManager 覆盖层

基于 NativePHP 官方文档翻译