Jer*_*mas 6 javascript asynchronous vue.js vuejs2
我有一个父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')
}
})
Run Code Online (Sandbox Code Playgroud)
我的fetch方法被多次调用.
Krz*_*sik 10
您可以v-if在父模板中使用:
<template v-if="everthingIsReady">
<child-item :data="data"></child-item>
</template>
Run Code Online (Sandbox Code Playgroud)
在everythingIsReady设置为之前,不会创建子项目true,您可以在所有呼叫完成后立即设置.
使用Promise.all。
在下面的代码中,我修改了您的fetch方法以从 ajax 调用返回承诺。然后,我们可以将这些 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))
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3126 次 |
| 最近记录: |