Dynamic & Async Components
Earlier, we used the attribute to switch between components in a tabbed interface:
When switching between these components though, you’ll sometimes want to maintain their state or avoid re-rendering for performance reasons. For example, when expanding our tabbed interface a little:
See the Pen Dynamic components: without keep-alive by Vue () on CodePen.
You’ll notice that if you select a post, switch to the Archive tab, then switch back to Posts, it’s no longer showing the post you selected. That’s because each time you switch to a new tab, Vue creates a new instance of the currentTabComponent
.
Check out the result below:
See the Pen by Vue (@Vue) on .
Now the Posts tab maintains its state (the selected post) even when it’s not rendered.
Check out more details on <keep-alive>
in the API reference.
Async Components
In large applications, we may need to divide the app into smaller chunks and only load a component from the server when it’s needed. To make that possible, Vue has a defineAsyncComponent
method:
You can also return a Promise
in the factory function, so with Webpack 2 or later and ES2015 syntax you can do:
You can also use defineAsyncComponent
when registering a component locally:
Async components are suspensible by default. This means if it has a in the parent chain, it will be treated as an async dependency of that <Suspense>
. In this case, the loading state will be controlled by the <Suspense>
, and the component’s own loading, error, delay and timeout options will be ignored.
The async component can opt-out of Suspense
control and let the component always control its own loading state by specifying suspensible: false
in its options.
You can check the list of available options in the API Reference