从API提取数据后,VueJS不会更新DOM吗?

dan*_*hao 1 vue.js vue-component vuejs2

我正在尝试创建有关照片列表的示例,并且在调用API之后将数据绑定到组件时遇到麻烦。

JS代码:

<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>
Run Code Online (Sandbox Code Playgroud)

HTML代码

<main id="photo_detail">
    <photo-list v-for="photo in photos" :photo="photo"></photo-list>
</main>
Run Code Online (Sandbox Code Playgroud)

从API获取所有照片后,据我了解,该变量photos将自动绑定,而VueJS将更新DOM。

VueJs 2.1.6

任何帮助。

谢谢!

Hel*_*and 6

问题在于您的this值内部function()具有该值的范围,axios而不是vue实例。或者您可以直接(response)=>使用this

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);
       });
   }
 })
Run Code Online (Sandbox Code Playgroud)

  • 很高兴它帮助了:)我自己在这个简单的问题上花了很多时间:D (2认同)