Reputation: 15
I'm loading a simple JSON file, assigning it to a reactive variable, and displaying it in the template. However, it only works partly.
{{ people }}
, {{ people.People }}
, and in a people.People
in a v-for
loop work as expected,
but accessing the people.People[0].FullName
fails. But why? Any insight is appreciated.
Here is my .json
{
"People": [
{
"FullName": "The Json"
}, {
"FullName": "The Jetsons"
}
]
}
And here is the component.vue
code
<template>
<h1>Test</h1>
<div>
<p>{{ people }}</p> <!-- Works and displays: { "People": [ { "FullName": "The Json" }, { "FullName": "The Jetsons" } ] } -->
<p>{{ people.People }}</p> <!-- Works and displays: [ { "FullName": "The Json" }, { "FullName": "The Jetsons" } ] -->
<p>{{ people.People[0].FullName }}</p> FAILS - Uncaught TypeError: $setup.people.People is undefined
<p v-for="(item, idx) in people.People" :key="idx">
{{ item.FullName }} <!-- Works as expected -->
</p>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
name: "Test",
setup() {
const people = ref({});
fetch('http://localhost:3000/data/people.json')
.then(response => response.json())
.then(data => people.value = data);
return {
people
}
}
}
</script>
<style>
</style>```
Thanks
Upvotes: 0
Views: 233
Reputation: 1260
At "setup time" before your json is loaded :
people = {}
, so people.People[Ø]
raises an error cause people.People
is not defined at this moment
In your exemple
{{ people }}
and {{ people.People }}
display something cause it's reactive and you just don't have time to see it before the json is loaded
There is several ways to manage this. ere is two of them
Add an if
<p v-if="people.People">{{ people.People[0].FullName }}</p>
Init with default walues
const people = ref({
People: []
});
Upvotes: 1