Search code examples
vue.jssocketsserversocket.iochat

how to place server action listeners in a vuejs project?


I am trying to make a simple chat app using vuejs and socketio. I would like to broadcast a message from one user to all the others. I have the following code on the server side to do that:

io.on('connection', socket => {
    socket.on('send-message', message => {
        console.log('message sent: ' + message)
        socket.broadcast.emit('receive-message', message)
    })
})

On the client side, I am listening to that action in this method:

this.socket.on('receive-message', message => {
        this.createMessageHtmlElement(message)
      })

I am having a hard time knowing where to place that method. putting in mounted() or created() will make it get called over and over again. I only want to call it when the server actually sends a message.
What is the correct way to place server action listeners in a vuejs project?


Solution

  • putting in mounted() or created() will make it get called over and over again.

    this.socket.on is a "socket version" of document.addEventListener (docs) so, you will set a function (callback) that will be executed when a certain event occurs (receive-message in your case). Depending on what createMessageHtmlElement actually does, you can put this.socket.on in either created() or mounted(). Assuming you have a simple app, probably the best place to do that is App.vue since the listener is going to be registered when the App.vue is registered (Vue lifecycle)