I am quite new to Vue and am attempting to retrieve a JSON response from an API and then print this on my page.
This is what I have so far:
<body>
<div id="mystats" class="container">
<h1>My Top Tracks</h1>
<ol>
<li v-for="track in tracks">@{{ track.name }}</li>
</ol>
<pre>@{{ tracks|json }}</pre>
<button v-on:click="fetchStats">Fetch stats</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.min.js"></script>
<script type="text/javascript">
$vue = new Vue({
el: '#mystats',
data: {
tracks: [],
},
methods: {
fetchStats: function()
{
this.$http.get('/mystatsdata', {params: {type: 'tracks'}}).then((response) => {
this.tracks.push(response.body);
console.log(this.tracks.name);
}, (response) => {
// error callback
});
}
}
})
</script>
</body>
Below is the response I am getting back:
[
[
{
"name": "Falling Away - Acoustic (Bonus Track)",
"track_number": 8,
"type": "track",
}
]
]
The issue is that the:
<ol>
<li v-for="track in tracks">@{{ track.name }}</li>
</ol>
is not printing out the track name.
There's no error in my console, and so being a little new to Javascript and Vue.js I'm not really sure where I am going wrong.
How do I get the name to display?
Edit
Here is the response with more than one entry (limited to 2 currently):
[
[
{
"name": "Falling Away - Acoustic (Bonus Track)",
"track_number": 8,
"type": "track",
},
{
"name": "Perfect Strangers",
"track_number": 1,
"type": "track",
}
]
]
The response that you are getting back is an array containing another array - which in turn contains the actual objects representing your tracks.
So inside: <li v-for="track in tracks">@{{ track.name }}</li>
, the track
refers to the inside array and not to each object.
For quick-fix, you can change your code to:
<li v-for="track in tracks[0]">@{{ track.name }}</li>
and try.
But the proper fix would be to fix the backend, to return the result as a single array of objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With