Find file Copy path
d9c5695 Dec 17, 2018
3 contributors

Users who have contributed to this file

@JingYenLoh @sdras @numb86
274 lines (244 sloc) 10.2 KB
title type order
Dynamic & Async Components

This page assumes you've already read the Components Basics. Read that first if you are new to components.

keep-alive with Dynamic Components

Earlier, we used the is attribute to switch between components in a tabbed interface:

<component v-bind:is="currentTabComponent"></component>

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:

{% raw %}

{{ tab }}
<script> Vue.component('tab-posts', { data: function () { return { posts: [ { id: 1, title: 'Cat Ipsum', content: '

Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats. Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs. My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around

' }, { id: 2, title: 'Hipster Ipsum', content: '

Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabby chic, street art knausgaard trust fund shaman scenester live-edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR&B hoodie plaid venmo. Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8-bit chartreuse. Trust fund food truck drinking vinegar gochujang.

' }, { id: 3, title: 'Cupcake Ipsum', content: '

Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake. Liquorice candy macaroon toffee cookie marzipan.

' } ], selectedPost: null } }, template: '\
    \ \ {{ post.title }}\ \

{{ selectedPost.title }}

\ \ Click on a blog title to the left to view it.\ \
\ ' }) Vue.component('tab-archive', { template: '
Archive component
' }) new Vue({ el: '#dynamic-component-demo', data: { currentTab: 'Posts', tabs: ['Posts', 'Archive'] }, computed: { currentTabComponent: function () { return 'tab-' + this.currentTab.toLowerCase() } } }) </script> <style> .dynamic-component-demo-tab-button { padding: 6px 10px; border-top-left-radius: 3px; border-top-right-radius: 3px; border: 1px solid #ccc; cursor: pointer; background: #f0f0f0; margin-bottom: -1px; margin-right: -1px; } .dynamic-component-demo-tab-button:hover { background: #e0e0e0; } .dynamic-component-demo-tab-button.dynamic-component-demo-active { background: #e0e0e0; } .dynamic-component-demo-tab { border: 1px solid #ccc; padding: 10px; } .dynamic-component-demo-posts-tab { display: flex; } .dynamic-component-demo-posts-sidebar { max-width: 40vw; margin: 0 !important; padding: 0 10px 0 0 !important; list-style-type: none; border-right: 1px solid #ccc; } .dynamic-component-demo-posts-sidebar li { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; cursor: pointer; } .dynamic-component-demo-posts-sidebar li:hover { background: #eee; } .dynamic-component-demo-posts-sidebar li.dynamic-component-demo-active { background: lightblue; } .dynamic-component-demo-post-container { padding-left: 10px; } .dynamic-component-demo-post > :first-child { margin-top: 0 !important; padding-top: 0 !important; } </style> {% endraw %}

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.

Recreating dynamic components is normally useful behavior, but in this case, we'd really like those tab component instances to be cached once they're created for the first time. To solve this problem, we can wrap our dynamic component with a <keep-alive> element:

<!-- Inactive components will be cached! -->
  <component v-bind:is="currentTabComponent"></component>

Check out the result below:

{% raw %}

{{ tab }}
<script> new Vue({ el: '#dynamic-component-keep-alive-demo', data: { currentTab: 'Posts', tabs: ['Posts', 'Archive'] }, computed: { currentTabComponent: function () { return 'tab-' + this.currentTab.toLowerCase() } } }) </script> {% endraw %}

Now the Posts tab maintains its state (the selected post) even when it's not rendered. See this fiddle for the complete code.

Note that `` requires the components being switched between to all have names, either using the `name` option on a component, or through local/global registration.

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 easier, Vue allows you to define your component as a factory function that asynchronously resolves your component definition. Vue will only trigger the factory function when the component needs to be rendered and will cache the result for future re-renders. For example:

Vue.component('async-example', function (resolve, reject) {
  setTimeout(function () {
    // Pass the component definition to the resolve callback
      template: '<div>I am async!</div>'
  }, 1000)

As you can see, the factory function receives a resolve callback, which should be called when you have retrieved your component definition from the server. You can also call reject(reason) to indicate the load has failed. The setTimeout here is for demonstration; how to retrieve the component is up to you. One recommended approach is to use async components together with Webpack's code-splitting feature:

Vue.component('async-webpack-example', function (resolve) {
  // This special require syntax will instruct Webpack to
  // automatically split your built code into bundles which
  // are loaded over Ajax requests.
  require(['./my-async-component'], resolve)

You can also return a Promise in the factory function, so with Webpack 2 and ES2015 syntax you can do:

  // The `import` function returns a Promise.
  () => import('./my-async-component')

When using local registration, you can also directly provide a function that returns a Promise:

new Vue({
  // ...
  components: {
    'my-component': () => import('./my-async-component')

If you're a Browserify user that would like to use async components, its creator has unfortunately [made it clear]( that async loading "is not something that Browserify will ever support." Officially, at least. The Browserify community has found [some workarounds](, which may be helpful for existing and complex applications. For all other scenarios, we recommend using Webpack for built-in, first-class async support.

Handling Loading State

New in 2.3.0+

The async component factory can also return an object of the following format:

const AsyncComponent = () => ({
  // The component to load (should be a Promise)
  component: import('./MyComponent.vue'),
  // A component to use while the async component is loading
  loading: LoadingComponent,
  // A component to use if the load fails
  error: ErrorComponent,
  // Delay before showing the loading component. Default: 200ms.
  delay: 200,
  // The error component will be displayed if a timeout is
  // provided and exceeded. Default: Infinity.
  timeout: 3000

Note that you must use Vue Router 2.4.0+ if you wish to use the above syntax for route components.