1

I am new in Vue.JS and I have tried to search the solution but nothing worked in my case.

I am using websocket to get data from server, when data coming I want to push it to a table row by row.

methods: {
    addRow: function(a, b) {
        var newRow = {
            no:++this.no,
            pos:a,
            uraian:b,
            jml:'N/A'
        }
        this.newPos.push(newRow);
    },
}

Function calling addRow() method is inside mounted:

mounted: function() {
    console.log('Starting connection to WebSocket Server');
    this.connection = new WebSocket('ws://localhost:8080/pos-detail');

    this.connection.onmessage = function(event) {
        console.log('Server message : ' + event.data);
        this.posArray = event.data.split(';');
        if(this.posArray.length > 2) {
            this.addRow(this.posArray[0], this.posArray[7]);
        }
    }
}

But, when data coming from server I got this error Uncaught TypeError: this.addRow is not a function.

Whats wrong with my code structure?

panoet
  • 3,608
  • 1
  • 16
  • 27
  • 2
    You're using a `function(event)` for the `onmessage` event, so `this` is not your component instance. Use an arrow function instead: `...onmessage = event => {` – Matt U Aug 26 '21 at 02:59
  • Thank you Matt, for giving direct answer and it solved the problem instead of closing the question and pointing to another thread with broader question. Appreciate!!! Hope you the best. – panoet Aug 26 '21 at 23:46

0 Answers0