2

I'm new to vue.js and here is my problem:

data: {
        ws: null, 
        newMsg: '',
        username: null,    
        usersList: '' 
    },
        created: function() {
        var self = this;
        this.ws = new WebSocket('ws://' + window.location.host + '/room');
        this.ws.addEventListener('message', function(e) {
            var msg = JSON.parse(e.data);
                if (msg.Message == "joined" ) {
                self.usersList.push(msg.Name); // <--Problem here 
              }


        });
    },

But I get this error in the browser console:

Uncaught TypeError: self.usersList.push is not a function

I've also tryied a fixed string instead of msg.Name but get the same error.

What's wrong here and how to fix it?

2
  • 1
    You declared as string usersList: '' in data, change it to usersList: []. Commented Mar 13, 2017 at 4:57
  • @MatJ Right. Just figured out! Please answer and I'll accept. Commented Mar 13, 2017 at 4:58

1 Answer 1

3

1.Use userList:[] as array, that you can use the push() method, see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

2.When your e.data is a array, like: [1,2,3,4], you can use concat to combine two array.

var arr1 = [1,2,3,4];
var arr2 = [5,6,7];
var arr = arr1.concat(arr2); // [1, 2, 3, 4, 5, 6, 7]

Or, Array.prototype.push.apply(arr1, arr2); to push all elements from a second array.

var arr1 = [1,2,3,4];
var arr2 = [5,6,7];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1);//[1, 2, 3, 4, 5, 6, 7]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.