【问题标题】:Vue.js: Uncaught (in promise) TypeError: $set is not a functionVue.js:未捕获(承诺)类型错误:$set 不是函数
【发布时间】:2017-06-25 01:12:26
【问题描述】:

我正在从 reddit API 获取 cmets 并尝试使用 $set 更新数组以便它可以更新视图,但我收到此错误:

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

虚拟机组件:

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

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    我已经设置了一个 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 应该能够跟踪数组上的推送调用:

    .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

    【讨论】:

    • ReferenceError: comments is not defined
    • 我做了你的编辑以防万一,但它仍然没有更新视图。我正在使用v-for 将它们打印出来,但它没有更新。
    • 对不起,完全忽略了 cmets 是一个数组。我推荐推送版本。
    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2022-09-24
    • 2018-04-15
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多