【问题标题】:Vue 2.0: Passing asynchronous data to child componentVue 2.0:将异步数据传递给子组件
【发布时间】:2017-12-17 00:12:31
【问题描述】:

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

【问题讨论】:

    标签: javascript asynchronous vue.js vuejs2


    【解决方案1】:

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

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

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

    【讨论】:

    • 我的问题是我多次调用fetch(),所以它会在第一次迭代时更新everythingIsReady
    • 简单高效,我喜欢...谢谢
    • 太棒了!谢谢!
    【解决方案2】:

    使用Promise.all

    在下面的代码中,我修改了您的 fetch 方法以从 ajax 调用返回承诺。然后,我们可以将这些承诺收集到一个数组中,并将它们传递给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))
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-13
      • 2017-07-14
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 2016-09-24
      相关资源
      最近更新 更多