Stephan-v
Stephan-v

Reputation: 20289

Vue check when async component has loaded

I am wondering how to check when an async component has loaded.

Normally I would load my component like so:

Vue.component(
     'booking-overlay', 
     () => import('@/components/BookingOverlayAsync.vue')
);

Using something like this does not work:

Vue.component(
   'booking-overlay',
    () => import('@/components/BookingOverlayAsync.vue').then(() => {
        console.log('component has loaded');
    })
);

It leads to the following error:

Uncaught (in promise) TypeError: Cannot read property '__esModule' of undefined at ensureCtor..

The component no longer loads but the promise does resolve though. By adding the then it no longer resolves the promise itself it seems.

How can I globally register this async component and also check when this components chunk of JavaScript has been loaded?

Obviously I could simply do this together with setting the global component:

import('@/components/BookingOverlayAsync.vue').then(() => {
    console.log('Chunk loaded');
});

This just seems like a very ugly solution though.

Upvotes: 4

Views: 3344

Answers (1)

Deng  Zhebin
Deng Zhebin

Reputation: 1262

Because your second promise object returned by .then function doesn't continue to hand down the async loaded component to vue lib itself.

the Vue.component function expects that the second parameter should be a function that returns a promise where the resolved data must be the async-loaded component itself.

please try following:

Vue.component(
        'booking-overlay',
        () => import('@/components/BookingOverlayAsync.vue').then(component => {
            console.log('component has loaded');
            return component;
        })
    );

Upvotes: 5

Related Questions