我想要实现的是在我的子组件中将数据作为 Prop 传递,但是这些数据是从服务器加载的,因此需要一段时间才能加载。
我现在只想在数据完全加载时安装子组件
所以目前正在这样做
在父组件中
<template>
<child-cmp :value="childdata"></child-cmp>
</template>
<script>
export default{
data(){
childdata : [];
},
methods:{
fetchINitData(){
//fetch from server then
this.childdata = res.data.items;
console.log(res.data.items) //has some values
}
}
components:{
childcmp
},
mounted(){
this.fetchINitData();
}
}
</script>
现在在我的子组件中
<script>
export default{
props:["value];
mounted(){
console.log(this.value) //this is always empty
}
}
</script>
从上面的示例中,作为 props 传递的数据在子组件上始终为空。我如何只在收到数据后挂载子组件,或者如何确保子组件获得最新的数据更改。
最佳答案
使用<template v-if="childDataLoaded">
,并在得到这样的数据后加载你的子组件
<template>
<template v-if="childDataLoaded">
<child-cmp :value="childdata"></child-cmp>
</template>
</template>
<script>
export default{
data(){
childDataLoaded: false,
childdata : [];
},
methods:{
fetchINitData(){
//fetch from server then
this.childdata = res.data.items;
this.childDataLoaded = true;
console.log(res.data.items) //has some values
}
}
components:{
childcmp
},
mounted(){
this.fetchINitData();
}
}
</script>
这是更新子组件的好方法。
var child = Vue.extend({
template: "<div>Child Component : {{name}} <div v-if='loading'>Loading...</div></div>",
props: ['name','loading']
});
var app = new Vue({
el: "#vue-instance",
data: {
name: "Niklesh",
loading: true
},
mounted() {
var vm = this;
setTimeout(function() {
vm.name = "Raut";
vm.loading = false;
}, 1000);
},
components: {
child
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script>
<div id="vue-instance">
<child :name="name" :loading="loading"></child>
</div>
关于javascript - Vuejs 仅在加载数据后挂载子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46731440/