The situation I'm facing is that the code in this example results in a blank screen, as shown in this jsfiddle. Even elements unrelated to the loop are not being displayed.
Here's a snippet of the HTML:
<div id="app">
<button @click="objectFromApi">
run objectFromApi function
</button>
<div
v-for="obj in myObject[0].results"
:key="obj.id"
>
<p>
{{ obj.message }}
</p>
</div>
</div>
This is a part of the JavaScript:
new Vue({
el: "#app",
data: {
myObject: []
},
methods: {
objectFromApi: function(){
this.myObject.push(
{
"count": 5,
"results": [
{
"id": 1,
"message": "object 1"
},
{
"id": 2,
"message": "object 2"
}
]
}
)
}
},
})
However, things work if:
1.)The objectFromApi
function is directly called in the created
lifecycle hook (which is not preferred)
created() {
this.objectFromApi()
}
2.) Or without using the created
life cycle hook by spreading out objects like this within the nested results
array (also not desired):
this.myObject.push(
...{
"count": 5,
"next": "http://127.0.0.1:8000/api/someurl/?page=2",
"previous": null,
"results": [
{
"id": 1,
"message": "object 1"
},
{
"id": 2,
"message": "object 2"
}
]
}.results
)
In option 2.), the v-for
loop should be adjusted as follows:
v-for="obj in myObject"
instead of v-for="obj in myObject[0].results"
What could possibly be wrong with the initial approach?