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

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

我的fetch方法被多次调用.

推荐答案

使用Promise.all.

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

Vue.js相关问答推荐

Vuetify快速失败不会阻止发送表单

如何使用composition api v-model Select 框获取其他JSON 值?

我需要在 nuxt2 上使用 /index 作为 url 的一部分

vue js如何将布尔值传到数据库

使用 vue / nuxt js 切换 fontawesome 图标

使用 cypress 进行 e2e 测试的 vuejs 期间出现 Webpack 错误

CssSyntaxError 使用 Webpack 4 构建未知单词

VueJS 插件的如何react式绑定?

确保在渲染组件之前加载 Vuex 状态

判断 vue-router.beforeEach 不限制对路由的访问

如何只查看数组中的一个对象?

一个 div 组件中的 Vue.js 2.0 路由链接

如何使表格行可点击并展开行 - vue.js - element-ui

不需要提交Mutations的 vuex 操作

使用 Vue.js 的用户可切换自定义主题

未捕获的类型错误:c.querySelectorAll 不是函数

所有 vue props和数据都给出错误 Property属性在 type 上不存在,带有 typescript

使用 Vue 的点击编辑文本字段

使用 Vuetify 的可滚动数据表

vue-cli@3 没有可用于依赖类型的模块工厂:CssDependency