0

I'm making a chat Application with VueJS, but when an user is sending a message it should be saved in an array. But this array is not getting any data. Here is my code:

The variable:

data() {
    return {
        messages: [],
    }
},

And the method I'm using:

sendMessage() {
    socket.emit('chat message', {name: this.name, message: this.message});
    this.message = '';
    socket.on('get message', function (msg) {
        this.messages += {
             "name":"" + msg.name + "",
             "message":"" + msg.message + "",
        };

        console.log(this.messages);
    });
}

But when the this.messages += function should add a json object. But in the Vue Tab in the browser it still says it's an empty array. What is going wrong here?

Jens Bouma
  • 149
  • 2
  • 11
  • 1
    at your end of the `socket.on()` method add `.bind(this)` like this `}.bind(this));` – bill.gates Jun 17 '20 at 08:54
  • Yess, that works @Ifaruki thank you! I didn't even know that.. – Jens Bouma Jun 17 '20 at 08:57
  • usually people just use arrow functions, that means instead of this `function(msg) {` they write like this `(msg) => {` and it works too, but remember, arrow functions dont work in internet explorer. In that case its just 1 argument, so you can write it like this `msg => {` – bill.gates Jun 17 '20 at 09:01
  • Oh yea, then you don't need the bind function I see. – Jens Bouma Jun 17 '20 at 09:03

0 Answers0