Pusher and Vue.js components not leaving channel when using Vue Router
Asked Answered
C

1

5

I'm using Pusher with Laravel Echo to create presence channels for certain areas in my application. All my front-end routing is done using Vue Router.

When switching between routes, Vue router will load certain components based on my routes settings. It works great, however, Pusher doesn't automatically disconnect the users from these channels. It will happen only if I run a full page refresh, which is not what I want.

In my component, the js code to join a Pusher channel is inside mounted, like this:

    data() {
        return {
            users: [],
        }
    },
    mounted() {
        Echo.join('transaction.' + this.tid)
            .here(users => {
                this.users = users;
                }
            })
            .joining(user => {
                this.users.push(user);
            })
            .leaving(user => {
                this.users.splice(this.users.indexOf(user), 1);
            });
    },
    methods: {
        // ...
    },

How do I disconnect the users from the channels using Vue Router routing, without refreshing the page?

Thank you.

Culberson answered 8/4, 2017 at 17:6 Comment(1)
Echo.leave('transaction.' + this.tid);?Wilden
K
7

I believe that Vue Router may keep the component instance alive for performance reasons. Because of that, the websocket channel could still be connected even when routing between components.

To prevent this issue, you can manually leave the channel using Vue's component destroyed method.

Since you are using Laravel's Echo, all you need to do is: Echo.leave('channel-name')

...
methods: {
    // ...
},
destroyed() {
    Echo.leave('transaction.' + this.tid);
}
Katzen answered 8/4, 2017 at 17:22 Comment(2)
i have the reverse case of this issue here @Katzen once i navigate to another route via vue-router then come back to my homepage i want it to load the list of all online users, but echo doesnt fire except i do a full page refresh #53693868Object
@dapo I posted an answer there for what I think it could fix the issue. I hope it helps.Katzen

© 2022 - 2024 — McMap. All rights reserved.