⚠️ This lesson is retired and might contain outdated information.

Switch Between Vue Components with Dynamic Components

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 9 months ago

A common scenario is to present different components based on the state of the application. Dynamic components in Vue make this simple by providing a component element that simply needs to be bound to the component that you want to render. This example shows using a select dropdown in Vue to select the component to render.

Instructor: [00:00] To demonstrate dynamic components, I created three functional components, each one just returning an h1 with a different background and text.

[00:09] I'm going to make an array of these on my component. I'll call these comps, let's say one, two, and three. Then, I'll have a selected comp, which can be this.comps, and describe the first one.

[00:21] I'll use a select drop-down right in here, select, and I'll set up a v-model. That's bound to the selected comp. The options for this will be looping through v-for, where we say comp in comps, we'll make the key the comp.name. The whole label can be the comp.name, as well. Of course, I need the value bound to the comp.

[00:49] We have our drop-down with one, two, and three. When I change that, it'll change the selected comp, which makes it easy to use the component, which is a reserved component name in Vue. I can bind is to selected comp.

[01:05] From here, it's easy to go one, two, three. Whenever I select a component, my is changes to the selected comp, which can be either this one, that one, or that one, because I'm simply providing this list and a model to my select drop-down, three, two, and one.