Search code examples
vuejs2updatesv-for

Vue v-for list does not update after data changed


The idea is simple: The Vue instance loads groups from an API. This groups are shown using a v-for syntax.

The groupdata is formatted properly, and added to app.groups using .push function, which should update the v-for list.

However, the v-for list will not update.

When I change v-for="group in groups" (loaded externally) to v-for="group in people" (already in the app), it does give output.

HTML

   <div id="app" class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
            <div class="panel-heading">Realtime Socket Chat</div>
                <div class="panel-body" v-if="dataReady" v-for="group in groups"> @{{ group.name }}
                    <a v-bind:href="group.link" class="pull-right">
                        <div class="btn btn-xs btn-primary">
                            Join
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

Vue

var app = new Vue({
    el: "#app",
    data: {
        groups: [],
        people: [{name: 'hi'}, {name: 'lol'}]
    },
    mounted: function() {
        this.load()
    },
    methods: {
        load: function() {
            axios.get('http://example.com/groups')
                .then(function (response) {

                console.log(response.data.groups);

                response.data.groups.forEach(function(group) {
                    app.groups.push(group);
                });

                // app.groups.forEach(function (group) {
                //    group.link = '/g/' + group.id + '/join';
                // });
                // console.log(response.data.groups);

                console.log(this.groups); //outputs [{...}, {...}] so this.groups is good
            })
            .catch(function (error) {
                this.errors.push(error);
                console.log(error);
            })
        }
    }

});

API

{

"groups": [ {

  "id": 1,
  "name": "Photography Chat",
  "created_at": "2017-11-26 08:50:16",
  "updated_at": "2017-11-26 08:50:16"
},

{
  "id": 2,
  "name": "Media Chat",
  "created_at": "2017-11-26 08:50:16",
  "updated_at": "2017-11-26 08:50:16"
}

]

}


Solution

  • A fact I left out in the question (because I assumed it would not matter) was that I am working within the Laravel framework, Laravel automatically imports Vuejs within main.js. Which does not play nice when Vue is loaded in additionally. I removed main.js and it works.