javascript - Vue.js:未捕获( promise )TypeError:$set 不是函数

标签 javascript vue.js

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

未捕获( promise )TypeError:$set 不是函数

虚拟机组件:

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

最佳答案

我已经设置了一个代码笔来演示这两种可能性: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); 
     });
 });

参见 https://v2.vuejs.org/v2/api/#vm-set用于 API 引用。

或者,您可以使用具有相同参数的全局 Vue.set 方法:

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

参见 https://v2.vuejs.org/v2/api/#Vue-set用于全局 API 引用。

关于javascript - Vue.js:未捕获( promise )TypeError:$set 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42095831/

相关文章:

javascript - 如何在javascript中将文字对象转换为用户定义的对象?

javascript - 如何从 defaultProps 迁移到默认参数

javascript - Vue 范围 : how to delay handling of @mouseover

javascript - Vue - 同时使用具有多个配置和不同名称的同一个插件?

vue.js - 选择选项后如何使用element-ui和vuejs触发 "select"的模糊事件?

vue.js - 现有 html 页面中的 Vue 组件

javascript - 如何获取 .js 文件本身的 uri

javascript - 检查 WebSocket 服务器是否正在运行(在本地主机上)

javascript - 这会成为竞争条件吗? (JavaScript)

javascript - Vue JS 基于复选框数组过滤结果