DD DD
DD DD

Reputation: 1238

How to avoid websocket clients duplicated using vuejs

When I access to a component, it runs socket.on.
And there is a button component in Vuejs as below. So when I emit to socket.on('voice') of nodejs, the nodejs socket emits to 'socket.on('reply').
Thus, console.log(msg) worsk well.

<button @click="start()">Click</button>

methods:{
   start(){
       socket.emit('voice',{data:'hey'})
   }
created(){
       socket.on('reply', msg => console.log(msg))

But the problem is when I move to another url and back to this component, 'socket.on('reply') runs again.
Therefore there are two websocket clients here.
how can I solve this problem? Thank you so much for reading this.

Upvotes: 0

Views: 403

Answers (1)

Gander
Gander

Reputation: 2001

I give you another link, where it is explained: Vue.js: Dynamic & Async Components

I know very little about views and dynamic content, but from what I understood from the documentation, you have to cover your component with a keep-alive block, which will cause that this component will not be regenerated again. You must consider all the pros and cons of this solution, in particular performance issues, and whether it can be done differently.

I don't know what your component looks like, so I give an example from the documentation:

<keep-alive>
  <my-chat-component></my-chat-component>
</keep-alive>

Upvotes: 1

Related Questions