簡體   English   中英

Vue 2.0:將異步數據傳遞給子組件

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

我有一個父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方法被多次調用。

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

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

everythingIsReady設置為true之前,不會創建子項,您可以在所有調用完成后立即設置。

使用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))
  }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM