Unmy_
Unmy_

Reputation: 485

Vue.component() dynamic import with loader

Is there a way to import dynamically a component with a Loader default if it's not loaded ?

We use something like this right now,

import Dashboard from '../components/dashboard';


Vue.component('dashboard', Dashboard);

I tried something like this as the documentation say link to the docs

import Loader from '../components/loader';
const Dashboard = () => ({
  component: import('../components/dashboard'),
  loading: Loader,
  delay: 500, //to test
})

Vue.component('dashboard', Dashboard);

Either way it doesn't seems to work

Upvotes: 0

Views: 382

Answers (1)

tony19
tony19

Reputation: 138696

Your code should already work. It might seem to not work because the loading happens instantaneously.

If you artificially delay the return of import('../components/dashboard'), you'll notice the loader displayed:

const delayed = async (promise) => {
  const result = await promise
  await new Promise(r => setTimeout(r, 2000))
  return result
}

Vue.component('Dashboard', () => ({
  component: delayed(import('./components/Dashboard.vue')),
  loading: Loader,
  delay: 500
}))

demo

Realistically, the dynamic component is intended for components that might take a significant amount of time to load (e.g., from a remote URL).

Upvotes: 1

Related Questions