简体   繁体   中英

Vue Websockets double

I have some problems using Laravel/Echo websockets with Vue.js. I have everything setup as needed, and it works, but not as expected. So the problem is that, when I refresh the page and send request it will show that request, but if I change a page and return to that page where is that websocket, it will double that request, and same will happen if I click on another route. Basically if I change page 5 times, it will show that websocket 5 times in that table, why is that? Here is my setup.

This is mounted method where I'm connecting to the channel.

mounted() {
        if(this.liveData){
            window.Echo.channel("addOrder").listen(".order-created", (order) => {
                this.$store.commit("ADD_ORDER", order);
            });
        }
        
        this.$store.dispatch("GET_ORDERS");
    },

and here is my connection in main.js

import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');
Pusher.logToConsole = true;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'some_key',
    wsHost: '127.0.0.1',
    wsPort: 6001,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: false,
    disableStats: true,
});

Your Echo is attached to window , Vue is not reloading page, it's just switching it with JS, so your connection stills alive.

You should disconnect before leaving page, so just do it in beforeDestroy hook. More about hooks here

Also if you need this connection everywhere you should not initialize it in mounted , created or elsewhere in Vue component, you can just create separate file or plugin for Vue, because that function will trigger each time you opening page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM