使用来自父级的 ajax 调用更新 vuejs 组件

Updating vuejs component with ajax call from the parent

VueJs 的新手。我想知道 how/where 我会调用 Ajax 来动态下拉数据以填充以下 Vue table 吗?

https://jsfiddle.net/yyx990803/xkkbfL3L/?utm_source=website&utm_medium=embed&utm_campaign=xkkbfL3L

我已经(粗略地)修改了上面的示例,如下所示:

var demo = new Vue({
  el: '#demo',
  data: {
    searchQuery: '',
    gridColumns: ['name', 'power'],
    gridData: []
  },
  methods: {
    fetchUsers: function() {
      ...
      // ajax call using axiom, fetches data into gridData like this:
      axios.get('http://localhost/url')
        .then(function(response) {
           this.gridData = response.data;
        })
        .catch(function(error) { console.log("error"); })
      ...
    }
  },
  created: function() {
    this.fetchUsers();
  }
})

我正在尝试合并这里的 ajax 部分:

https://jsfiddle.net/chrisvfritz/aomd3y9n/

我添加了 fetchUser 方法,该方法调用 ajax 来拉取数据。我能够使用 fetch 和 axiom 提取我的数据并将其打印到控制台,所以我知道这部分有效。

但是,我的数据从未出现或更新过。 table 加载空白。我认为这与我将方法和创建的钩子放在 Vue 模型对象(demo)上,而不是放在组件本身上有关。但是我不太确定如何修改示例来解决它,因为示例从父级传递数据。

谁能给我一些指导?

你的问题就在这里:

.then(function(response) {
     this.gridData = response.data;
})

在你的匿名函数中,你没有你期望的上下文。最简单的解决方案是在方法中添加 .bind(this).

.then(function(response) {
    this.gridData = response.data;
}.bind(this))

通过添加它,您的方法主体将知道外部上下文,并且您可以访问您的组件数据。