[英]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.