我在JS / Vue中有一个数组,我希望在<ul>
/ <li>
标签中显示,并在数组获取新元素时保持更新。
HTML:
<ul id="ulist">
<li v-for="user in users">
@{{ user }} <!-- "@" needed since this is in a laravel project with blade templates -->
</li>
</ul>
JS:
<script>
var socket = io('localhost:3000');
new Vue({
el: "#ulist",
data: {
users: []
},
mounted: function() {
this.$nextTick(function() {
socket.on('test-action', function(data) {
this.users.push(data.username);
console.log(data.username);
}.bind(this));
});
}
});
</script>
正确填充了数组(我可以通过console.log语句看到),但<li v-for="user in users">...
部分似乎没有工作,因为没有创建任何<li>...</li>
元素。我在这做错了什么?
只是为了澄清:如果我向用户数组添加硬编码值,那些值在<li>
元素中显示得很好,但没有添加到数组中的其他值(在mounted
函数中)显示在<li>...</li>
元素中。
编辑:版本是2.5.13,如果重要的话
你能试试吗?
<script>
var socket = io('localhost:3000');
new Vue({
el: "#ulist",
data: {
users: []
},
mounted: function() {
var _self = this;
this.$nextTick(function() {
socket.on('test-action', function(data) {
self.users.push(data.username);
console.log(data.username);
}.bind(this));
});
}
});
</script>
问题在于你的this
变量的范围。在你的代码中这一行:
this.users.push(data.username);
限定为ajax请求中的函数调用,如果使用() =>
,它将保持当前范围在您的方法中的上下文中。此外,你不应该在挂载的呼叫中需要nextTick
所以试试这个:
<script>
var socket = io('localhost:3000');
new Vue({
el: "#ulist",
data: {
users: []
},
mounted: function() {
socket.on('test-action', data => {
this.users.push(data.username);
console.log(data.username);
});
}
});
</script>
虽然您使用的是bind(this)
,但您在this
中使用了nextTick
,这导致了范围问题。
另一件值得注意的事情,列表需要一个key在vue v ?? (我不记得是哪个)所以最好在使用v-for
时添加一个键:
<ul id="ulist">
<li v-for="(user, index) in users" :key="index">
@{{ user }} <!-- "@" needed since this is in a laravel project with blade templates -->
</li>
</ul>