首页 > 解决方案 > 从 API 获取数据后,VueJS 不更新 DOM?

问题描述

我正在尝试创建一个关于照片列表的示例,并且在调用 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>

HTML 代码

<main id="photo_detail">
    <photo-list v-for="photo in photos" :photo="photo"></photo-list>
</main>

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

VueJs 2.1.6

任何帮助。

谢谢!

标签: vue.jsvuejs2vue-component

解决方案


问题在于您的this值在function()其中该值的范围为axios而不是 vue instance 。或者你可以直接(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);
       });
   }
 })

推荐阅读