2

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

1

You have a couple problems:

  • Your JSON file isn't valid. The trailing commas after the the false cause the parser to choke.

  • You aren't parsing your JSON (which is why you probably didn't see the JSON error). Once you fix the JSON file, you need to parse it with something like this.exam = JSON.parse(data) rather than assigning the string to this.exam

  • Once you do that, you can test for the object in the template with v-if before trying to access its properties:
    <h1 v-if="exam.questions">Questions length: {{ exam.questions.length }}</h1>

v-if will prevent the attempt to access exam.questions.length until the ajax request has returned data

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks for the reply Mark_M. The subject is that if I want to enter a new condition using a computed property the same error reappears: "TypeError: this.exam.questions is undefined": Modified example: https://jsfiddle.net/9gw2Luax/29/
I found a solution: jsfiddle.net/9gw2Luax/30 I think the problem was at the point of the first render template exam.questions property does not exist yet (because asynchrony of setting data). But when if I defined the structure of data with no assigment then properties exists and there were no errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.