Vue-Socket.io icon indicating copy to clipboard operation
Vue-Socket.io copied to clipboard

create connection on a single component

Open quiquelhappy opened this issue 5 years ago • 3 comments

Hello! I want to connect to the socket server only when rendering a particular component, and remain disconnected when that component is visible. It would be ideal if the connection was created on the mounted() event, it could be something like: import vueSocket from 'vue-socketio';

...
mounted() {
 vueSocket.startConnection("loginstring",opts)
}

My website connects to multiple socket servers depending for multiple components...

quiquelhappy avatar Aug 18 '20 15:08 quiquelhappy

Hey, I have been using a workaround for this.

just add this snippet in the mounted of the component.

In component.

//Setting auth creds
this.$socket.io.opts.query = {token : res.data.token};
//To open the socket connection
this.$socket.open();

In main.js make sure to set auto-connect false

export let SocketInstance = socketio(socketUrl,{
    autoConnect: false
});

Vue.use(VueSocketIO, SocketInstance);

And Whenever you want to close the connection. this.$socket.close()

avy-sha avatar Aug 23 '20 16:08 avy-sha

Hello! Do you know if it is also possible to change the URL to connect to into the component? Thank you so much for this already though!

quiquelhappy avatar Aug 23 '20 17:08 quiquelhappy

Hey I have not personally tried this but I found this on StackOverflow and it seems right to me. https://stackoverflow.com/a/47445931/6530182

Just replace the this.$socket instance with a new one with a modified URL. Hope it works.

avy-sha avatar Aug 23 '20 17:08 avy-sha