如何在Nuxt 3中实现Laravel Echo/Pusher集成?
在Nuxt 3中集成Laravel Echo与Pusher实现实时通知
不用纠结Nuxt 2的适配库,Nuxt 3可以直接通过原生依赖+自定义插件实现,步骤如下:
1. 安装核心依赖
直接安装官方包即可,无需第三方Nuxt插件:
npm install laravel-echo pusher-js # 或使用yarn yarn add laravel-echo pusher-js
2. 创建客户端专属插件
在plugins目录下新建echo.client.ts(后缀.client确保仅在浏览器端运行),内容如下:
import { defineNuxtPlugin } from '#app' import Echo from 'laravel-echo' import Pusher from 'pusher-js' // 全局挂载Pusher,供Laravel Echo调用 window.Pusher = Pusher export default defineNuxtPlugin((nuxtApp) => { const config = useRuntimeConfig() const echo = new Echo({ broadcaster: 'pusher', key: config.public.pusherAppKey, cluster: config.public.pusherCluster, forceTLS: true, // 根据你的Pusher配置调整 authEndpoint: `${config.public.apiBaseUrl}/broadcasting/auth`, // Laravel授权端点,私有/ presence频道必填 withCredentials: true // 使用Sanctum认证时需开启 }) // 将Echo实例注入Nuxt应用,方便组件调用 nuxtApp.provide('echo', echo) })
3. 配置环境变量与Runtime Config
在项目根目录.env文件中添加Pusher配置:
NUXT_PUBLIC_PUSHER_APP_KEY=你的Pusher密钥 NUXT_PUBLIC_PUSHER_CLUSTER=你的Pusher集群(如ap1) NUXT_PUBLIC_API_BASE_URL=https://你的Laravel后端地址
在nuxt.config.ts中配置runtimeConfig:
export default defineNuxtConfig({ runtimeConfig: { public: { pusherAppKey: process.env.NUXT_PUBLIC_PUSHER_APP_KEY, pusherCluster: process.env.NUXT_PUBLIC_PUSHER_CLUSTER, apiBaseUrl: process.env.NUXT_PUBLIC_API_BASE_URL } } })
4. 在组件中使用(Composition API)
在任意Vue组件的setup中调用$echo监听通知事件:
<template> <div class="notifications"> <div v-for="notification in notifications" :key="notification.id"> {{ notification.message }} </div> </div> </template> <script setup> const { $echo } = useNuxtApp() const notifications = ref([]) // 监听公开频道的通知事件 $echo.channel('notifications') .listen('NotificationSent', (event) => { notifications.value.push(event.notification) // 可在此添加弹窗、音效等提示逻辑 }) // 私有频道示例(需后端授权) // $echo.private(`user.${userId}`) // .listen('PrivateNotification', (event) => { // notifications.value.push(event.notification) // }) // 组件卸载时销毁监听 onUnmounted(() => { $echo.channel('notifications').stopListening('NotificationSent') }) </script>
关键注意事项
- 确保Laravel后端已正确配置广播:启用
BroadcastServiceProvider,事件实现ShouldBroadcast接口,频道名称与前端一致 - 使用私有/ presence频道时,后端
broadcasting/auth端点需正确处理认证(如Sanctum需配置CORS允许凭证) - 核对Pusher控制台的应用密钥、集群与前端配置一致,确认连接状态正常
内容的提问来源于stack exchange,提问作者Hussam
相关产品推荐
相关产品推荐

