简体   繁体   English

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

[英]Updating vuejs component with ajax call from the parent

New to VueJs. VueJ的新手。 I'm wondering how/where would I make an Ajax call to pull data dynamically down to populate the following Vue table? 我想知道如何/在哪里进行Ajax调用以动态下拉数据以填充以下Vue表?

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

I've (roughly) modified the example above as follows: 我(大致)修改了上面的示例,如下所示:

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

I'm trying to incorporate the ajax pieces from here: 我正在尝试从此处合并ajax文件:

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

I've added the fetchUser method which makes the ajax call to pull the data down. 我添加了fetchUser方法,该方法进行ajax调用以提取数据。 I'm able to pull down my data and print it to the console using both fetch and axiom, so I know that part works. 我可以使用提取和公理来提取数据并将其打印到控制台,所以我知道这部分工作。

However, my data never appears or updates. 但是,我的数据永远不会出现或更新。 The table loads blank. 该表加载空白。 I think it has something to do with me putting the method and created hook on the Vue model object (demo), rather than on the component itself. 我认为这与将方法和创建的钩子放在Vue模型对象(演示)上而不是组件本身有关。 But I'm not quite sure how to modify the example to resolve it, as the example passes the data in from the parent. 但是我不太确定如何修改示例以解决该问题,因为该示例将数据从父级传入。

Can someone give me some guidance? 有人可以给我一些指导吗?

You problem is right over here: 您的问题就在这里:

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

Within your anonymous function within your then you don't have the context you expect. 在您内部的匿名函数中,您将没有期望的上下文。 The most simple solution is adding a .bind(this) to the method. 最简单的解决方案是在方法中添加.bind(this)

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

By adding it your method body will be aware of the outer context and you can access your components data. 通过添加它,您的方法主体将了解外部上下文,并且您可以访问组件数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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