Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS does not update DOM after fetch data from API?

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!

like image 955
dangchithao Avatar asked Sep 05 '25 03:09

dangchithao


1 Answers

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);
       });
   }
 })
like image 181
Helping hand Avatar answered Sep 07 '25 19:09

Helping hand