N
N
Nik_Set_72018-04-18 13:14:14
Vue.js
Nik_Set_7, 2018-04-18 13:14:14

How to asynchronously import child components into parent in vue?

Please tell me: there is the following component

<template>
  <div class="homePage">
    <header class="header">
      <HeaderComponent></HeaderComponent>
    </header>

    	<div class="homePage__block">
    	  	<div class="homePage__account">
        <account></account>
    	  	</div>
    	</div>
  </div>
<template>

<script>
  export default {
    components: { 
      HeaderComponent: () => import('../layout/header-main.vue'),
    },
                mounted () {
                        console.log("Test")
                }
       }
</script>

In the child element, I have information loaded via axios and I need to make sure that the child component first receives the information, and then it is displayed in the "Test" console.
Installed babel-plugin-syntax-dynamic-import and created .babelrc file in project root.
The code above does not work as expected: there are no errors, but "Test" is displayed first, and then there is information about getting information in the child component.
How can this be fixed?
UPD:
1. The question did not correctly indicate: it should have indicated "synchronously"
2. An additional common event bus was needed to solve the problem. Those. it will connect to both the parent and child components. Detailed description here:
https://alligator.io/vuejs/global-event-bus/
https://medium.com/@modex13/vue-js-2-%D0%BF%D0%B5%...
3. In the child, specify anywhere we need, and in the parent in crated
https:/ /en.vuejs.org/v2/guide/instance.html#%D0%94...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
fl3nkey, 2018-04-18
@Nik_Set_7

Well, this is the point of loading components asynchronously, the parent will not wait until the child asynchronous component is loaded and will call mounted . I see several options.
1. Load the component synchronously.
2. Use $

<template>
  <p>Child component</p>
</template>

<script>
export default {
  mounted() {
    //имитируем задержку
    setTimeout(() => {
      this.$emit('load');
    }, 2000);
  }
}
</script>

<template>
    <h1>Parent component</h1>
    <child @load="onLoad"></child>
</template>

<script>
export default {
  components: {
    child: () => import('child.vue'),
  },
  methods: {
    onLoad() {
      console.log('Child loaded!');
    }
  }
}
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question