简体   繁体   中英

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

I'm fetching comments 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 component:

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

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 component itself:

.then(function(response){
     // Overwrite comments array directly with new data
     vm.$set(vm, 'comments', 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 comments
     vm.comments = [];

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

See https://v2.vuejs.org/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, 'comments', response.body.data.children);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM