无法在 laravel 的客户端监听推送器事件

问题描述 投票:0回答:0

我在 laravel 中使用 pusher 来广播消息。 Laravel 能够将消息发送到推送器通道。但是我无法在客户端收听事件。

我正在使用 Larave,惯性,vuejs。

我创建了一个 NewChatMessage 事件,它将广播消息。在节目聊天中,我正在使用监听事件,这并没有发生。

Bootstrap.js

import _ from 'lodash';
window._ = _;

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

import Echo from 'laravel-echo';

import Pusher from 'pusher-js';
window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    wsHost: 'ws-ap2.pusher.com',
    wsPort: 80,
    forceTLS: false,
    enabledTransports: ['ws'],
    cluster:import.meta.env.VITE_PUSHER_APP_CLUSTER,
    disableStats: true
});

NewChatMessage.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Models\Message;
use App\Models\User;
use App\Models\Company;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class NewChatMessage implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    public $user;
    public $company;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user,Message $message)
    {
        $this->user = $user;
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('chat'.$this->message->chatroom_id);
    }

    public function broadcastAs()
    {
        return "message.new";
    }
}

聊天室.vue

<script setup>
import { Link, usePage, useForm } from "@inertiajs/inertia-vue3";
import { ref, onMounted } from "vue";
import ReceivedMessageCard from "@/Components/ReceivedMessageCard.vue";
import SentMessageCard from "@/Components/SentMessageCard.vue";
import ClipIcon from "@/Icons/ClipIcon.vue";
import EllipsisHorizontal from "@/Icons/EllipsisHorizontal.vue";
import PaperAirPlaneIcon from "@/Icons/PaperAirPlaneIcon.vue";
import UploadIcon from "@/Icons/UploadIcon.vue";
import UserIcon from "@/Icons/UserIcon.vue";
import ChatRoomLayout from "@/Layouts/ChatRoomLayout.vue";
import axios from "axios";

const props = defineProps({
    confirmsTwoFactorAuthentication: Boolean,
    sessions: Array,
    chatroom: Object,
    messages: Object,
    auth_member: Object,
    readBy: Object,
});

const page = usePage();

const showOptions = ref(false);
const message = ref(null);

const form = useForm({
    file: null,
});

const chatroomMessages = ref(props.messages);
// setInterval(function(){
//     getMessages()
// }, 1000);

onMounted(() => {
    scroll(0);
    connect();
});

const connect = () => {
    window.Echo.private("chat."+props.chatroom.id).listen(".message.new", (e) => {
        console.log("inside");
    });

};

const scroll = (height) => {
    var objDiv = document.getElementById("container");
    objDiv.scrollTop = objDiv.scrollHeight + height;
};

const getMessages = async () => {
    await axios
        .get(route("enquiry.chatroom.show", { chatroom: props.chatroom }))
        .then((res) => {
            chatroomMessages.value = res.data;
        });

    scroll(20);
};
const sendMessage = () => {
    if (message.value !== null && message.value !== "") {
        axios
            .post(route("chatroom.newMessage", { id: props.chatroom.id }), {
                message: message.value,
            })
            .then((res) => {
                if (res.status === 201) {
                    message.value = "";
                    getMessages();
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }
};
const uploadFile = () => {
    showOptions.value = false;
    form.post(route("chatroom.fileUpload", { id: props.chatroom.id }));
};

const shareDetails = () => {
    message.value =
        "Email: " +
        page.props.value.user.email +
        " Number: " +
        page.props.value.user.number;
    sendMessage();
    showOptions.value = false;
};
</script>
laravel vue.js pusher inertiajs
© www.soinside.com 2019 - 2024. All rights reserved.