Pusher Laravel 广播离开房间通知

Pusher Laravel Broadcast Leave Room Notification

我将 post 我的应用程序中的所有方法,只是为了让我清楚地阅读。这是目标。当用户进入房间时,会添加一条消息“用户已进入房间” - 效果很好。现在,我想做的是当用户离开房间时,我希望它说“用户已离开房间”——通知有效,但它显示错误的用户名(它显示了看到消息的人的用户名.

我缺少或没有把握的是什么

    methods: {
        connect() {
            if (this.currentRoom?.id) {
                let vm = this;
                this.getMessages();
                Echo.join("chat." + this.currentRoom.id)
                    .here(users => {
                        this.sendUserActivityNotification(this.$page.props.user, true)
                        this.users = users
                        this.usersCount = users.length
                    })
                    .joining(user => {
                        this.users.push(user)
                        this.usersCount = this.usersCount+1
                    })
                    .leaving(user => { 
                        this.sendUserActivityNotification(this.$page.props.user, false)
                        this.users = this.users.filter(({id}) => (id !== user.id))
                        this.usersCount = this.usersCount-1
                    })
                    .listen('NewChatMessage', (e) => {
                        vm.getMessages();
                    });
            }
        },
        setRoom(room) {
            this.currentRoom = room;
        },
        getMessages() {
            axios.get('/chat/room/' + this.currentRoom.id + '/messages')
                .then(response => {
                    this.messages = response.data;
                })
                .catch(error => {
                    console.log(error);
                })
        },
        sendUserActivityNotification(user, joining) {
            const message = `${user.name} has ${joining === true ? 'entered' : 'left'} the room.`
            return axios.post(`/chat/room/${this.currentRoom.id}/notifications`, {message}).then(() => this.getMessages())
            .catch(console.error)
        },
        leaveRoom({id}) {
            this.$store.dispatch(RoomTypes.LEAVE_ROOM, id)
        }
    },

我没有使用过 Laravel Echo,但是在阅读了你的代码后我认为在 leaving 方法调用中,当你传递当前用户而不是你从事件中接收到的内容时调用 sendUserActivityNotification 方法。

您的实现如下所示:

    ...
    .leaving(user => { 
        this.sendUserActivityNotification(this.$page.props.user, false)
        this.users = this.users.filter(({id}) => (id !== user.id))
        this.usersCount = this.usersCount-1
    })
    ....

您正在将 this.$page.props.user 传递给 this.sendUserActivityNotification 方法,而不是传递 user

您必须将该调用更改为 this.sendUserActivityNotification(user, false)