Reputation: 1277
I'm working on a Vue app, this is my first SPA and a lot of concepts are not completely clear to me yet.
In one component i'm creating a websocket connection like that:
created(){
this.connection = new WebSocket('ws://MY-URL);
this.connection.onmessage = (event) => {
console.log(event)
}
}
This works without any problem, but suppose that i navigate to a different url in my spa, the websocket connection will not be closed, which means that even though i don't need to receive websocket messages (since i'm on a different page) i will keep receiving them, which is not really good for resource usage on the client side.
Other than that, if i navigate again to the original component where the websocket connection is started, another connection will be created, which means that i'm going to have two websocket connections sending the same messages at the same time. Why isn't the connection closed once the page is left? How can i close it, then?
Upvotes: 1
Views: 4407
Reputation: 310
simply use this if you want to close websocket connection on component close, or changes,
unmounted() {
this.connection.close();
this. Connection = null; // to prevent memory leacking
console.log("Closing connection to WebSocket Server")
},
Upvotes: 1
Reputation: 88
It sounds like you are using vue-router. To navigate to another route, you may use Navigation guards within your component to handle your code.
For example, if your current route loads Page.vue, add the following nav-guard to it:
beforeRouteLeave(to, from, next) {
// called when the route that renders this component is about to
// be navigated away from.
// has access to `this` component instance.
//this.connection is your ws
this.connection.close()
next()
}
Upvotes: 4