Swappable Dynamic Components in Vue.js

Have you ever needed to switch between various arbitrary components at the same mount point in Vue.js? Sure, it’s not a super common problem, but it’s the sort of things you’d have to do if you implemented your own router, or some sort of container component that you didn’t want to use slots in. I personally ran into this use-case once with an Angular 2 app, and actually never solved it (because I ported said app to Vue shortly after.)

Anyway, it’s quite simple to do in Vue by using the <component></component> tag.

Introducing the <component></component> Tag

Conceptually, the <component> tag is incredibly simple. It just takes a string (or component definition) :is prop. Vue then looks up the component referenced by that string and renders it in place of the <component> tag. Don’t let the simplicity fool you though, the number of use-cases it unlocks is remarkable.

Example Usage:

<template>
  <component :is="dynamicComponent"></component>
</template>

<script>

// Register another component to render in this one dynamically.
import Vue from 'vue';

Vue.component('some-other-component', {
  template: `<p>Wheee</p>`
});

export default {
  data: () => ({
    dynamicComponent: `some-other-component`
  })
}
</script>

Or simplify things by using just a component definition:

<template>
  <component :is="dynamicComponent"></component>
</template>

<script>
export default {
  data: () => ({
    dynamicComponent: {
      template: `<p>Wheee</p>`
    }
  })
}

</script>

Or reactively switch components with computed properties…

<template>
  <component :is="dynamicComponent"></component>
</template>

<script>
export default {
  props: {
    value: Boolean
  },

  computed: {
    dynamicComponent() {
      if(value) {
        return 'component-special';
      } else {
        return 'component-default';
      }
    }
  }
}
</script>

And, of course, you can render components passed in props or anything else accessible from the Vue instance.

Keep-alive

Right now, any component rendered with <component> will be destroyed entirely when a different component is rendered in its place, and re-created if it is re-added. This is not always ideal, which is why the <keep-alive> component was introduced.

If you wish for components rendered with the <component> tag (or rendered in conditionals) to keep from being destroyed when they’re no longer being rendered, just wrap the <component> tag in a <keep-alive> tag like so:

<template>
  <div>
    <keep-alive>
      <component :is="dynamicComponent"></component>
    </keep-alive>
  </div>
</template>
✖ Clear

🕵 Search Results

🔎 Searching...