4

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.

4

1 回答 1

6

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);
}
于 2017-04-08T17:22:38.163 回答