Home > Mobile >  Vue3: Displaying of nested JSON object data does not work
Vue3: Displaying of nested JSON object data does not work

Time:10-05

i am trying to display data from a nested JSON object. The data is retrieved correctly from axios but I dont get it to be displayed.

The json object looks like this:

{
        "id": "1",
        "name": "Germany",
        "continent": "Europe"
        "president": {
            "id": "12",
            "name": "Joanna Doe",
        }
}

In the vue component the data is saved in the "country" object.

. . .
data() {
   country: {},
}

If I then try to render it in vue template, I get all the data if I render following:

<p>{{ country }}</p>

But if I do try to render the data of the nested "president" attribute like this:

<p>{{ country.president.name }} </p>

I get following error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')
    at Proxy.<anonymous> (CountryDetail.vue:25)
    at renderComponentRoot (runtime-core.esm-bundler.js:1165)
    at componentEffect (runtime-core.esm-bundler.js:5184)
    at reactiveEffect (reactivity.esm-bundler.js:42)
    at effect (reactivity.esm-bundler.js:17)
    at setupRenderEffect (runtime-core.esm-bundler.js:5137)
    at mountComponent (runtime-core.esm-bundler.js:5096)
    at processComponent (runtime-core.esm-bundler.js:5054)
    at patch (runtime-core.esm-bundler.js:4660)
    at componentEffect (runtime-core.esm-bundler.js:5191)

Is there anyway how to render this nested data?

Thanks!

CodePudding user response:

You are missing a comma , after "continent": "Europe" <- right here.

Your code should work. See this example

CodePudding user response:

country is initially an empty object (and later updated), but your template tries to render the nested properties immediately in:

<p>{{ country.president.name }} </p>

That results in an error because country.president initially does not exist, so it's undefined, leading to the error of reading name from undefined.

One way to solve this is to conditionally render that <p> only when country.president is defined:

<p v-if="country.president">{{ country.president.name }}</p>

Alternatively with Vue 3, you could use optional chaining to avoid the runtime error. However, the <p> element would still be rendered with an empty body. (If the empty tag is undesired, stick with the conditional rendering solution above.)

<p>{{ country.president?.name }}</p>
  • Related