Vue-Socket.io
Vue-Socket.io copied to clipboard
create connection on a single component
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...
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()
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!
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.