如何在Vuetify(Vue 2)应用中监听Laravel 5.5私有频道广播事件
Hey there! Let's walk through getting your Vuetify app listening to Laravel's private Pusher channels step by step—we’ll start with the basics to lock in the foundation, then move to setting up the service worker for local notifications.
1. First, Verify Laravel's Broadcast Configuration
Let’s make sure your backend is set up to send events to Pusher. It’s easy to miss a small config step, so let’s check off each item:
- In your
.envfile, confirm these Pusher settings are correct (replace with your actual Pusher credentials):BROADCAST_DRIVER=pusher PUSHER_APP_ID=your-app-id PUSHER_APP_KEY=your-app-key PUSHER_APP_SECRET=your-app-secret PUSHER_APP_CLUSTER=your-cluster # e.g., us2, eu1 - Uncomment
App\Providers\BroadcastServiceProvider::classinconfig/app.php—this enables Laravel’s broadcasting system. - Create your broadcast event (e.g.,
NewNotificationEvent) and implementShouldBroadcast(orShouldBroadcastNowif you don’t want queue delays). Define your private channel in thebroadcastOnmethod:namespace App\Events; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Queue\SerializesModels; class NewNotificationEvent implements ShouldBroadcast { use SerializesModels; public $message; public function __construct($message) { $this->message = $message; } // Define the private channel users will subscribe to public function broadcastOn() { return new PrivateChannel('user.'.auth()->id()); } } - Set up channel authorization in
routes/channels.php—this tells Laravel which users can access the private channel:Broadcast::channel('user.{userId}', function ($user, $userId) { // Only allow the user themselves to access their private channel return (int) $user->id === (int) $userId; });
2. Set Up Vuetify/Vue Frontend to Listen
Now let’s get your Vue app connected to Pusher and subscribed to the private channel:
- Install a compatible version of
pusher-js(Vuetify 1.5 works best with v4.x to avoid Vue 2 compatibility issues):npm install pusher-js@4.x - Initialize Pusher in your Vue app (I recommend putting this in a dedicated service file or
src/main.js):import Pusher from 'pusher-js'; // Initialize Pusher with your credentials const pusher = new Pusher('your-pusher-app-key', { cluster: 'your-cluster', // Laravel's built-in endpoint to authorize private channel access authEndpoint: '/broadcasting/auth', auth: { // Pass Laravel's CSRF token to avoid authorization errors headers: { 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content } } }); // Get the authenticated user's ID (pass this from Laravel to the frontend first) // Add this to your blade template: <script>window.authUser = { id: {{ auth()->id() }} };</script> const userId = window.authUser.id; // Subscribe to the private channel const privateChannel = pusher.subscribe(`private-user.${userId}`); // Listen for your event privateChannel.bind('App\\Events\\NewNotificationEvent', function(eventData) { console.log('Received event:', eventData); // Test this first—if you see this log, basic listening is working! });
3. Add Service Worker for Background Local Notifications
Once basic listening works, let’s set up the service worker to handle notifications even when the app is in the background:
- Register the service worker in your Vue app (add this to
main.js):if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/sw.js') .then(registration => { console.log('Service worker registered:', registration); // Send Pusher credentials to the service worker after registration registration.active.postMessage({ type: 'INIT_PUSHER', appKey: 'your-pusher-app-key', cluster: 'your-cluster', userId: window.authUser.id, csrfToken: document.querySelector('meta[name="csrf-token"]').content }); }) .catch(err => { console.error('Service worker registration failed:', err); }); }); } - Create the
public/sw.jsfile (service workers run in a separate context, so we pass credentials from the main app):// Import Pusher from CDN (service workers can't use npm modules directly) importScripts('https://js.pusher.com/4.4/pusher.min.js'); // Listen for the init message from the main app self.addEventListener('message', (event) => { if (event.data.type === 'INIT_PUSHER') { const { appKey, cluster, userId, csrfToken } = event.data; // Initialize Pusher in the service worker const pusher = new Pusher(appKey, { cluster: cluster, authEndpoint: '/broadcasting/auth', auth: { headers: { 'X-CSRF-Token': csrfToken } } }); // Subscribe to the private channel and listen for events const channel = pusher.subscribe(`private-user.${userId}`); channel.bind('App\\Events\\NewNotificationEvent', (data) => { // Show a local notification self.registration.showNotification('New Alert', { body: data.message, icon: '/icons/icon-192x192.png', // Replace with your icon path vibrate: [200, 100, 200] }); }); } });
Troubleshooting Quick Wins
- Check Pusher Dashboard: Use the Pusher Debug Console to confirm events are being sent and channels are subscribed to correctly.
- 403 Authorization Errors: Double-check your
routes/channels.phplogic to ensure the user is allowed access to the channel. - CSRF Issues: Make sure your frontend is sending the CSRF token correctly—Laravel’s
webmiddleware requires it for the channel auth endpoint. - Version Conflicts: Stick to
pusher-jsv4.x with Vue 2/Vuetify 1.5—newer versions may have breaking changes.
内容的提问来源于stack exchange,提问作者axsor
相关产品推荐
相关产品推荐

