In an attempt to create a messaging system that shows alerts of messages to different users, I have implemented Vue Socket Io from https://www.npmjs.com/package/vue-socket.io. However, the issue lies in the fact that the alerts are not being triggered as expected. Even though the client is successfully subscribed to an event in mounted, named after their userID, the message sent from the server does not display the alert.
Server:
io.on('connection', function(socket) {
socket.on('sendMessage', function (data) {
console.log("Sending message to" + data.user);
socket.emit(`CHAT_${data.user}`, data.msg)
});
});
Client:
In the client side implementation, the userIDSelf
is passed in as a prop indicating the logged-in user's ID. In the mounted()
hook, the client subscribes to a custom chat channel with their userID appended to it.
mounted() {
this.sockets.subscribe(`CHAT_${this.userIDSelf}`, (data) => {
alert(data)
});
},
Furthermore, there is a sendMessage()
function which retrieves input values from two fields on the template. The first field requires the recipient's user ID while the second field contains the actual message. These values are then sent to the backend server.
methods: {
sendMessage() {
this.$socket.emit('sendMessage', {user: this.userIDReceiver, msg: this.message})
},
}