0

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.

3
  • 1
    <keep-alive><your-component></your-component></keep-alive> Commented Dec 9, 2019 at 6:34
  • Thank you so much for your reply. But could you write some code in detail a little bit? Commented Dec 9, 2019 at 7:47
  • 1
    If you define socket.on('reply', msg => console.log(msg)) in Parent component then it won't call everytime. If App.vue is the Parent component then define there. Commented Dec 9, 2019 at 11:20

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.