How to render data with AJAX in Vuejs 2?

Viewed 2079

I have problems while trying to set data in a Vue instance
(example in: https://jsfiddle.net/a5naw6f8/4/ )

I assign the values to data property by AJAX. I can render exam object but when I want to access to an inner array exam.questions.length I get an error:

"TypeError: exam.questions is undefined"

This is my code :

// .js
new Vue({
    el: '#app',
    data:{
        id: "1",
        exam: {}
    },
    created: function () {
        this.fetchData();
    },
    methods: {
        fetchData: function () {
            $.get("https://dl.dropboxusercontent.com/s/15lkz66wy3fut03/data.json", 
                (data) => {
                    this.exam = data;
                }
            );
        }
    }
});

<!-- .html -->
<div id="app">
    <h1>ID: {{ id }}</h1>
    <h1>Exam: {{ exam }}</h1>

    <!--  exam.questions array is undefined -->
    <!-- <h1>Questions length: {{ exam.questions.length }}</h1> -->
</div>

I found a similar problem but it was relative to this reserved word scope: Vuejs does not render data from ajax

Does someone know how to fix this problem?

1 Answers
Related