Hotdry.
web

在 Laravel Inertia 中集成 Toast 通知:支持 Vue 和 React 的 SPA 无刷新反馈

通过 laravel-inertia-toast 库,实现 Laravel + Inertia 应用的 toast 通知,支持后端 PHP 和前端 JS 调用,提供多位置、多 toast 配置,无需页面刷新。

在现代 Web 应用开发中,Laravel 结合 Inertia.js 构建的单页应用(SPA)越来越流行。Inertia 允许使用 Vue 或 React 等前端框架,同时保持 Laravel 的后端逻辑。然而,提供用户友好的反馈如成功、错误或警告通知常常需要额外的处理。传统的 flash 消息在页面重定向时有效,但对于 SPA 风格的无刷新交互,后端 roundtrip 会打断用户体验。laravel-inertia-toast 库完美解决了这个问题,它是一个专为 Laravel + Inertia 设计的 toast 通知包,支持 Vue 3 和 React 适配器,提供流畅的 PHP API 和客户端钩子,实现真正的 SPA 反馈机制,无需额外后端请求。

为什么选择 laravel-inertia-toast?

这个库的核心优势在于其 “redirect-safe” 和 “multi-toast” 支持。“An opinionated package that provides beautiful toast notifications for Laravel + Inertia.js applications.” 通过 Inertia 的 props 机制,后端可以直接注入 toast 数据,前端渲染动画效果。即使在重定向或页面导航中,toast 也能持久显示,避免丢失。相比通用 toast 库如 Vue Toastification 或 React Hot Toast,它深度集成 Inertia,无需手动同步状态,支持 Tailwind CSS 样式,动画丝滑。

关键参数包括:

  • duration: 默认 5000ms,可自定义每个 toast 的自动消失时间。
  • position: 6 种位置(top-right、top-left 等),适应不同布局。
  • max_visible: 最大同时显示 toast 数,默认 5,避免屏幕 overcrowding。

这些参数确保通知不干扰用户操作,同时提供高自定义性。

安装与配置步骤

集成过程简单,分三步:后端 PHP 包、前端适配器、Tailwind 配置。

  1. 安装 PHP 包(核心闪存逻辑):

    composer require veekthoven/laravel-inertia-toast
    

    可选发布 config:

    php artisan vendor:publish --tag=inertia-toast-config
    

    config/inertia-toast.php 中调整全局参数:

    return [
        'duration' => 5000,
        'position' => 'top-right',
        'max_visible' => 5,
        'prop_key' => 'toasts',
    ];
    
  2. 安装前端适配器

    • Vue 3:
      npm install @laravel-inertia-toast/vue
      
    • React:
      npm install @laravel-inertia-toast/react
      
  3. Tailwind CSS 配置(必备,确保样式生成): Tailwind v4:在 resources/css/app.css 添加:

    @source "../../node_modules/@laravel-inertia-toast/vue/dist/**/*.js";  // Vue 示例
    

    Tailwind v3:在 tailwind.config.js

    module.exports = {
        content: [
            // ...
            './node_modules/@laravel-inertia-toast/vue/dist/**/*.js',
        ],
    };
    

这些步骤确保库在 Laravel 10+、Inertia v2.3.3+、PHP 8.1+ 环境下稳定运行。

后端使用:PHP API 调用

后端触发 toast 最简单,通过 Facade 或 Helper,在 Controller 中注入 Inertia props。

  • Facade 示例(推荐,简洁):

    use InertiaToast\Facades\Toast;
    
    public function updateProfile(Request $request) {
        // 更新逻辑...
        Toast::success('Profile updated!');
        return redirect()->route('dashboard');
    }
    

    支持类型:success()error()info()warning(),并带自定义 duration:

    Toast::success('Saved!', 3000);
    
  • Helper 示例(链式 fluent):

    toast('Slow message.')->duration(10000)->warning();
    

在重定向或 Inertia::render () 前调用,toast 数据会自动闪存到前端 props,避免 roundtrip 延迟。

前端集成与客户端触发

前端 setup 嵌入布局,无侵入性。

  • Vue 3: 在 resources/js/app.js

    import { createApp } from 'vue';
    import { InertiaToast } from '@laravel-inertia-toast/vue';
    
    const app = createApp(App);
    app.use(InertiaToast, {
        duration: 5000,
        position: 'top-right',
        max_visible: 5,
    });
    app.mount('#app');
    

    布局模板:

    <template>
      <div>
        <slot />
        <Toasts />
      </div>
    </template>
    

    组件内使用:

    <script setup>
    import { useToast } from '@laravel-inertia-toast/vue';
    const { success } = useToast();
    </script>
    
  • React: 在 app.tsx

    import { ToastProvider, Toasts } from '@laravel-inertia-toast/react';
    
    root.render(
        <ToastProvider config={{ position: 'top-right', duration: 5000, maxVisible: 5 }}>
            <App {...props} />
            <Toasts />
        </ToastProvider>
    );
    

    Hook 使用:

    import { useToast } from '@laravel-inertia-toast/react';
    const { success } = useToast();
    

客户端 toast 如复制操作:success('Copied!'),无需后端,纯 SPA 反馈。

高级用法与最佳实践

  • 多 Toast 队列max_visible: 3 防止堆叠,优先级高者先显示。

  • 自定义样式:Tailwind 类扩展,覆盖动画 transition-all duration-300

  • 监控与回滚

    参数 推荐值 监控点 回滚策略
    duration 4000-6000ms 用户跳过率 >20% 缩短至 3000ms
    position top-right 移动端遮挡 切换 bottom-center
    max_visible 3-5 同时 >5 发布 v1 更新,降级通用 alert
  • 性能优化:仅在需要时加载 adapter,结合 Inertia 页面级 props。

  • 测试:Pest/PHPUnit 中 mock Toast facade,模拟 Toast::success() 调用。

实际落地清单:

  1. 验证环境:Laravel 11 + Inertia 2 + Vue 3.4。
  2. 集成后测试重定向场景:后端 toast 在新页持久。
  3. A/B 测试 position 参数,追踪用户互动率。
  4. 生产监控:Sentry 捕获 toast 渲染错误。

此集成让 Inertia 应用获得原生 SPA toast 体验,提升 UX 无缝。

资料来源

(正文字数约 1250)

查看归档