- Learn by example
Make an RPG
Vue Implementations

Example of How to use keep-alive with Dynamic Components

Let's create two sections, where each one contains some text.

<div id="demo"> <button @click= 'thing = thing === "text0" ? "text1" : "text0"'> toggle text </button> <component v-bind:is="thing"></component> </div>
Vue.component('text0', { template: `<div>Text 0: <textarea></textarea> </div>` }); Vue.component('text1', { template: `<div>Text 1: <textarea></textarea> </div>` }); var app = new Vue({ el: '#demo', data: { thing: 'text0' } });

Go ahead and run this code. Enter some text into the text area and click "toggle text". The problem is whenever you toggle, the textarea looses it's state which can be a problem when you're switching between tabs.

The solution is to wrap the component in a built-in keep-alive tag. This keeps the state and prevents the component from being re-render everytime.

<keep-alive> <component v-bind:is="thing"></component> </keep-alive>

Now, try it again. Notice, whatever you type into the textarea is maintained even as you switch back and forth between the two components.

Example 2

Before you do this section, make sure you know how to use v-for.

Next, let's look at another example, where we're adding things dynamically to the page to two components. To one component we're adding trees. To another we're adding bushes. This is a fairly common pattern where each component represents a different main section of a website or CMS.

<div id="demo"> <button @click= 'thing = thing === "bushes" ? "trees" : "bushes"'> toggle thing </button> <component v-bind:is="thing"></component> </div>
Vue.component("trees", { template: `<div>Make trees: <button @click="trees.push(trees.length);"> Make a Tree</button> <div v-for="tree in trees" v-bind:key="tree" >A tree</div> </div>`, data: function() { return { trees: [1,2,3] } } }); Vue.component("bushes", { template: `<div>Make bushes: <button @click="myBushes.push(myBushes.length);"> Make a Bush</button> <div v-for="bush in myBushes" v-bind:key="bush" >A Bush</div> </div>`, data: function() { return { myBushes: [6,7,8] } } }); var app = new Vue({ el: "#demo", data: { thing: "bushes" } });

Once again, the solution is to surround the component with a keep-alive tag which maintains the state of the components inside of it as they're swapped in and out.

<keep-alive> <component v-bind:is="thing"></component> </keep-alive>

In the next lesson, we will learn about Example of how to use Async Components

Get the Latest Tutorial Updates
<< >>