Vue.js仅在数据加载后才安装子组件 [英] Vuejs mount the child components only after data has been loaded

查看:26
本文介绍了Vue.js仅在数据加载后才安装子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图实现的是将数据作为道具传递给我的子组件,但此数据是从服务器加载的,因此加载需要一段时间.

What am trying to achieve is to pass data as props in my children components but this data is loaded from the server so it takes a while to load.

我现在只想在数据完全加载后挂载子组件

I would now like to only mount the children components when the data is fully loaded

SO目前正在这样做

在父组件中

<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传递的数据在child组件上始终为空.我该如何仅在接收到数据后才挂载子组件,或者如何确保子组件获得最新更改的数据.

As from the above example the data passed as props is always empty on the children component. How do i only mount the child component after data has been received or how do i ensure that the childs component get the latest data changed.

推荐答案

使用<模板v-if ="childDataLoaded"> ,并在获取此类数据后加载您的子组件

Use <template v-if="childDataLoaded">,And load your child component after getting data like this

<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>

这是一种更新子组件的好方法.

Here is the Nice and cleaner way to update child component.

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>

这篇关于Vue.js仅在数据加载后才安装子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆