Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Switch Between Vue Components with Dynamic Components

    John LindquistJohn Lindquist

    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.

    vueVue.js
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss