Vue.js 2.5列表渲染

问题描述 投票:0回答:2

我在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,如果重要的话

javascript laravel vue.js vuejs2
2个回答
1
投票

你能试试吗?

<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>

1
投票

问题在于你的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>
© www.soinside.com 2019 - 2024. All rights reserved.