Vue 2.0:将异步数据传递给子组件

时间:2017-07-12 13:59:58

标签: javascript asynchronous vue.js vuejs2

我有一个父Vue组件,它通过prop将数据传递给它的子组件,但是数据是异步可用的,因此我的子组件使用未定义的值初始化。

在数据可用之前,我该怎么做才能阻止初始化?

父:

  var employees = new Vue({
    el: '#employees',
    data: { ... },
    methods: {
      fetch: function(model, args=null) {

      let url = "/" + model + ".json"
      console.log(url);
      $.ajax({
        url: url,
        success: ((res) => {
          console.log(res)
          this[model] = res;
          this.isLoading = false;
        error: (() =>  {
          this.isLoading = false;
        }),
        complete: (() => {
          // $('.loading').hide();
          this.isLoading = false;
        })
      })

    },
    mounted: function() {
      this.fetch(...)
      this.fetch(...)
      this.fetch('appointments')
    }
  })

我的fetch方法被多次调用。

2 个答案:

答案 0 :(得分:8)

您可以在父模板中使用v-if

<template v-if="everthingIsReady">
    <child-item :data="data"></child-item>
</template>

everythingIsReady设置为true之前,不会创建子项,您可以在所有通话完成后立即设置。

答案 1 :(得分:4)

使用Promise.all

在下面的代码中,我修改了fetch方法以从ajax调用返回promise。然后,我们可以在数组中收集这些promise并将它们传递给Promise.all,并在所有的ajax调用完成后执行某些操作。在这种情况下,请设置isLoading属性,以便在子组件上使用v-if

var employees = new Vue({
  el: '#employees',
  data: { isLoading: true },
  methods: {
    fetch(model, args=null) {
      let url = "/" + model + ".json"
      const success = res => this[model] = res
      const error = err => console.log(err)
      return $.ajax({url, success, error})
    }
  },
  mounted(){
    let promises = []
    promises.push(this.fetch('stuff'))
    promises.push(this.fetch('otherstuff'))
    promises.push(this.fetch('appointments'))
    Promise.all(promises)
      .then(() => this.isLoading = false)
      .catch(err => console.log(err))
  }
})
相关问题