Georgiy Santonov
Georgiy Santonov

Reputation: 13

Vue Router: fetching data from server (asynchronously with ajax) does not update the view in component

I have the following component (template):

<script type="text/x-template" id="student-list">

    <div v-if="studentList">
    <table>
        <tr v-for="student in studentList">
            <td>{{student.studentId}}</td>
            <td>{{student.studentName}}</td>
        </tr>
    </table>
    </div>
    </script>

For which I am fetching data like this, with an ajax request. The idea is that at "created" moment, there will be a request, then the StudentList property on component will update the moment data is fetched, and it should update in the view, too. Yet nothing happens. In console, it shows the proper data, but doesn't update the view.

var StudentList = Vue.component("student-list", {
        template: "#student-list",
        data: function() {
            return {
                studentList: null,
                
                ...
            }
        },
            created: function() {
            var self = this;
            this.ajaxRequest("get-student-list", {data: ''}, (studentList) => {
                
                self.studentList = JSON.parse(studentList).message;
                console.log(self.studentList);
                
                // shows the proper fetched data - but the studentList on component doesn't update
                
                // self.studentList, as shown in console, looks like this:
                // 
                // [{"studentId":"34732847328463","studentName":"Marian V. Johnson"},{"studentId":"3473584732463","studentName":"John A. Marian"},{"studentId":"347328341463","studentName":"Martin C. Johnson"}]
            });
        }

self.studentList shows the data that are supposed to show up in the view, but in the view itself, nothing shows. I followed the data fetching guide from Vue docs, it seems to be the same thing I am doing - yet it doesn't work.

What could be the issue?

Upvotes: 0

Views: 33

Answers (1)

Taro
Taro

Reputation: 126

Hi I would suggest to use the mounted hook instead of the created one. As you will see in the lifecycle diagram under the official docs the virtual DOM will be re-rendered only when you're on a mounted state.

enter image description here

Upvotes: 1

Related Questions