[英]How to add item to list in vue.js
I'm new to vue.js and here is my problem: 我是vue.js的新手,这是我的问题:
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. 我也尝试了固定字符串而不是
msg.Name
但是得到了同样的错误。
What's wrong here and how to fix it? 这是怎么了?如何解决?
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 1.使用
userList:[]
作为数组,可以使用push()
方法,请参见此处: 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. 2.当
e.data
是数组时,例如: [1,2,3,4]
,可以使用concat
合并两个数组。
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);
或者,
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.