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.
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() {
return {
dynamicComponent: `some-other-component`
}
}
}
</script>
Or simplify things by using just a component definition:
<template>
<component :is="dynamicComponent"></component>
</template>
<script>
export default {
data() {
return {
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.
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>
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!