最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue.js: Uncaught (in promise) TypeError: $set is not a function - Stack Overflow

programmeradmin1浏览0评论

I'm fetching ments from the reddit API and trying to update an array with $set so it can update the view, but I get this error:

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

VM ponent:

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

I'm fetching ments from the reddit API and trying to update an array with $set so it can update the view, but I get this error:

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

VM ponent:

export default {
  name: 'top-header',
  ponents: {
      Comment
  },
  data () {
    return {
      username: '',
      ments: []
    }
  },
  methods: {
      fetchData: function(username){
          var vm = this;
          this.$http.get(`https://www.reddit./user/${username}/ments.json?jsonp=`)
          .then(function(response){
              response.body.data.children.forEach(function(item, idx){
                  vm.ments.$set(idx, item); 
              });
          });
      }
  }
}
Share Improve this question asked Feb 7, 2017 at 17:06 frostyfrosty 2,8516 gold badges42 silver badges66 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

I've set up a codepen to demonstrate the two possibilities: http://codepen.io/tuelsch/pen/YNOqYR?editors=1010

The $set method is only available on the ponent itself:

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

or, since Vue.js sould be able to trace the push call on an array:

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

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

See https://v2.vuejs/v2/api/#vm-set for the API reference.

Alternatively, you can use the global Vue.set method with the same parameters:

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

See https://v2.vuejs/v2/api/#Vue-set for the global API reference.

发布评论

评论列表(0)

  1. 暂无评论