PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] how to place server action listeners in a vuejs project?

 October 22, 2022     chat, server, socket.io, sockets, vue.js     No comments   

Issue

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)



Answered By - Zarko
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing