[Vuejs]-Vue.js 2.5 list rendering

2👍

Can you try this ?

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

2👍

The problem is with the scope of your this variable. In your code this line:

this.users.push(data.username); 

is scoped to the function call within the ajax request, if you use () => it will keep the current scope in context within your method. Also, you shouldn’t need nextTick within the mounted call so try this:

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

Although you were using bind(this) you were using this within nextTick which was causing scope issues.

Another thing worth noting, lists require a key in vue v?? (I can’t remember which) so it’s best to add a key when using 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>

Leave a comment