简体   繁体   English

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

[英]Vue 2.0: Passing asynchronous data to child component

I have a parent Vue component that passes data to its child through a prop, but the data is available asynchronously and so my child component initializes with undefined values. 我有一个父Vue组件,通过prop将数据传递给它的子,但数据是异步可用的,因此我的子组件初始化为未定义的值。

What can I do to prevent initialization until the data is available? 在数据可用之前,我该怎么做才能防止初始化?

Parent: 家长:

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

My fetch method is called multiple times. 我的fetch方法被多次调用。

You can just use v-if in your parent template: 您可以在父模板中使用v-if

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

Child Item won't be created until everythingIsReady is set to true and you can set it right after all your calls complete. everythingIsReady设置为true之前,不会创建子项,您可以在所有调用完成后立即设置。

Use Promise.all . 使用Promise.all

In the code below, I modified your fetch method to return the promise from the ajax call. 在下面的代码中,我修改了您的fetch方法以从ajax调用返回promise。 We can then collect those promises in an array and pass them to Promise.all and do something when all of the ajax calls have completed. 然后我们可以在数组中收集这些promise并将它们传递给Promise.all并在所有 ajax调用完成后执行某些操作。 In this case, set the isLoading property so that you can use v-if on your child component. 在这种情况下,请设置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))
  }
})

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

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