【问题标题】:Updating vuejs component with ajax call from the parent使用来自父级的 ajax 调用更新 vuejs 组件
【发布时间】:2017-05-09 05:40:43
【问题描述】:

VueJs 新手。我想知道如何/在哪里进行 Ajax 调用以动态下拉数据以填充以下 Vue 表?

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 提取我的数据并将其打印到控制台,所以我知道这部分有效。

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

谁能给我一些指导?

【问题讨论】:

    标签: ajax vue.js vuejs2 vue-component


    【解决方案1】:

    你的问题就在这里:

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

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

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

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

    【讨论】:

    • 做到了。谢谢!
    猜你喜欢
    • 2017-06-18
    • 1970-01-01
    • 2021-07-23
    • 2017-12-31
    • 2019-03-20
    • 2021-07-30
    • 2017-04-16
    相关资源
    最近更新 更多