Jaime Jones

Frontend focused full stack enthusiast.

Keep-Alive Components

12 March 2020

Keep-alive components are a great tool availble to use in Vue. How often do we use layouts that utilize tabs? If you’re like me, the answer is frequently. Being able to separate out relevant information into sections and tab through as needed is great. And using keep-alive components in that kind of markup can be very helpful - but what exactly are keep-alive components?

For use with dynamic components

To understand keep-alive components, we first need to understand dynamic components. Dynamic components allow us to use a single <component> tag to render a component dynamically by binding a value to :is.

You can do something like the following:

<component :is="currentTab"></component>

The above example will render whatever component the currentTab is, as long as that value is the name of a registered component or is a component’s options object.

Combining with keep-alive

<button @click="setView('PuppyCmp')">See puppies!</button>
<button @click="setView('KittenCmp')">See kittens!</button>

<keep-alive>
  <component :is="activeView"></component>
</keep-alive>
export default {
  components: { PuppyCmp, KittenCmp },
  data() {
    return {
      activeView: 'PuppyCmp'
    }
  },
  methods: {
    setView(view) {
      this.activeView = view;
    }
  }
}

In this example, we have a view that we can switch between a PuppyCmp and a KittenCmp by utlizing dynamic components. Normally, this would re-mount the active component each time it is switched. But in this case, we’ve wrapped the <component> tag in <keep-alive>. So what does this do?

Well, this actually caches the state of the non-active components! This means that if I am currently viewing the PuppyCmp, switch to the KittenCmp and then switch back to the PuppyCmp, the component state will be the same as when I was previously viewing it, and the component will not re-initialize, so the various hooks around creation and mounting will not run again.

The pros and cons

By having a component that maintains its previous state, we can leverage powerful tabbed views that do not reset on the user switching the active tab. That being said, it is important to not over utilize keep-alive in cases where we would want a user to have a fully re-initialized component instance so as not to be working with stale data.

It is also important to note that keep-alive is meant to be used with a single active component, so it will not work with v-for and if there are v-if conditionals, only one condition can be met at a time for it to work properly.

Even with those caveats, keep-alive is a powerful tool to allow users to switch between views such as tabs while preserving the component state of each tab.