I am trying to create an example about the list of photos and I see a trouble when binding data to the component after call API.
JS code:
<script>
// photo item
Vue.component('photo-item', {
props: ['photo'],
template: `<li>{{ photo.name }}</li>`
});
// List of photos
Vue.component('photo-list', {
props: ['photos'],
template: `
<ul id="photo-list">
<photo-item v-for="photo in photos" :photo="photo"></photo-item>
</ul>`
});
new Vue({
el: "#photo_detail",
data: {
photos: []
},
created: function() {
axios
.get('/api/photos')
.then(function (response) {
this.photos = response.data; // Data existed
})
.catch(function (err) {
console.log(err);
});
}
})
</script>
HTML code
<main id="photo_detail">
<photo-list v-for="photo in photos" :photo="photo"></photo-list>
</main>
After fetching all photos from API and as my understand then the variable photos
will auto binding and VueJS will update DOM.
VueJs 2.1.6
Any help.
Thanks!
Issue is with your this
value inside function()
which has this value scoped to axios
instead of vue instance .
or you can use (response)=>
to use this
directly
new Vue({
el: "#photo_detail",
data: {
photos: []
},
created: function() {
var self=this;
axios
.get('/api/photos')
.then(function (response) {
self.photos = response.data; // Data existed
})
.catch(function (err) {
console.log(err);
});
}
})
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