I started using Vue JS 3 and I would like to know if I can and its possible to import component ( modals ) during the runtime I tried that but didn't work
watch:{
modal:{
handler(newModal){
App.component('modal', () => import(newModal))
}
}
},
CodePudding user response:
You can read about "Async Components" on the official Vue 3 documentation.
Basically, you can register a component as asynchronous, and it will lazyload itself when it tries to render the first time.
Simple defineAsyncComponent
<template>
<div>
<Modal v-if="open" />
</div>
</template>
<script>
export default {
components: {
MySyncComponent,
Modal: defineAsyncComponent(() => import('./Modal.vue'))
}
}
</script>
Using <script setup>
:
<script setup>
const Modal = defineAsyncComponent(() => import('./Modal.vue'))
</script>
Specifying custom lazyloading options:
const Modal = defineAsyncComponent({
loader: () => import('./Modal.vue'),
loadingComponent: ProgressSpinner,
delay: 150, // waits 150ms before showing the loading spinner
errorComponent: ErrorComponent,
timeout: 2000 // if not loaded before 2s, will show error
})
Using <Suspense>
wrapper component:
With the Suspense
component, all child component will be treated as asynchronous by default. They will be in their own chunk of code.
<Suspense>
<Modal v-if="open"> <!-- Loading as asynchronous -->
<template #fallback>
Loading...
</template>
</Suspense>