Vuejs mount the child components only after data has been loaded

后端 未结 2 1335
梦如初夏
梦如初夏 2020-12-15 17:48

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

相关标签:
2条回答
  • 2020-12-15 18:38

    Just Bind key to child-cmp you get reactive output. this is simplest method of reactivity in Vue js.

    <template>
      <child-cmp :key="childdata" :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>
    
    0 讨论(0)
  • 2020-12-15 18:53

    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>

    0 讨论(0)
提交回复
热议问题