2017-02-07 9 views
2

reddit APIからコメントを取得していて、ビューを更新できるように$ setを使用して配列を更新しようとしていますが、 :

Uncaught (in promise) TypeError: $set is not a function

VMコンポーネント:

export default { 
    name: 'top-header', 
    components: { 
     Comment 
    }, 
    data() { 
    return { 
     username: '', 
     comments: [] 
    } 
    }, 
    methods: { 
     fetchData: function(username){ 
      var vm = this; 
      this.$http.get(`https://www.reddit.com/user/${username}/comments.json?jsonp=`) 
      .then(function(response){ 
       response.body.data.children.forEach(function(item, idx){ 
        vm.comments.$set(idx, item); 
       }); 
      }); 
     } 
    } 
} 

答えて

2

は、私は2つの可能性を実証するためのcodepenを設定している:http://codepen.io/tuelsch/pen/YNOqYR?editors=1010

$セット法はONLですコンポーネント自体で使用可能なY:

.then(function(response){ 
    // Overwrite comments array directly with new data 
    vm.$set(vm, 'comments', response.body.data.children); 
}); 

または、Vue.jsは、アレイ上のプッシュコールを追跡することができるのでsould:

.then(function(response){ 
    // Clear any previous comments 
    vm.comments = []; 

    // Push new comments 
    response.body.data.children.forEach(function(item){ 
     vm.comments.push(item); 
    }); 
}); 

は、APIの参照用https://vuejs.org/v2/api/#vm-setを参照してください。

また、あなたは同じパラメータでグローバルVue.setメソッドを使用することができます。

import Vue from 'vue'; 
// ... 
Vue.set(vm, 'comments', response.body.data.children); 

グローバルAPIリファレンスのためhttps://vuejs.org/v2/api/#Vue-setを参照してください。

+1

これは 'ReferenceError:comments is not defined'を返しています – frosty

+0

私はあなたの編集を行いましたが、まだビューを更新していません。私はそれらを印刷するために 'v-for'をやっていて、更新されません。 – frosty

+0

申し訳ありませんが、コメントは配列です。私はプッシュバージョンをお勧めしたいと思います。 – phippu

関連する問題