Vue.js:Uncaught(承诺)TypeError:$ set不是函数

时间:2017-02-07 17:06:33

标签: javascript vue.js

我从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); 
              });
          });
      }
  }
}

1 个答案:

答案 0 :(得分:2)

我已经设置了一个codepen来演示两种可能性:http://codepen.io/tuelsch/pen/YNOqYR?editors=1010

$ set方法仅适用于组件本身:

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

或者,因为Vue.js能够跟踪数组上的push调用:

.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

相关问题