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

Dynamic Vue.js Components with the component element

Greg Thoman
InstructorGreg Thoman
Share this video with your friends

Social Share Links

Send Tweet

You can dynamically switch between components in a template by using the reserved <component> element and dynamically bind to its is attribute. By using <keep-alive> you can tell Vue to keep the component in memory.

[00:00] First, let's create a new x template with an ID of dino show. We'll add a wrapper div, a bolded dino name, and diet. Let's create a new template snippet called dino show. The template attribute will point to our new x template, dino show. We need access to the props name and diet. We'll add dino show to our components block.

[00:24] Let's create a dino show component in the view just to make sure everything's hooked up correctly. We'll set v bind name to item.text and v bind diet to item.diet.

[00:34] Let's add an attribute to our root component called current view and set it to dino edit. Let's move our v bind diet attribute to the dino edit component to make sure that we have all the data we need for both components to operate. Instead of using dino edit component, let's change it to a generic component.

[00:53] We'll bind is to current view. By changing current view, we can change which component is rendered.

[01:01] Let's set up a toggle so the user can switch between show and edit. We'll set up our spans v on click to toggle and display toggle label. We'll need to add a methods block and a toggle function that reads the current view and returns the opposite. Then we can add a computed block with the function toggle label that will return a string of show or edit based on the current view.

[01:25] Right now we have a problem. When we switch views, view is throwing away our data in the components. By wrapping our component in keep alive, we can tell view to keep the components and their data in memory.