Caching your Dynamic components with Vue Keep-Alive

518 VIEWS

·

When working with dynamic components, Vue recreates a new instance of a component when you switch the value of the is directive. While it’s useful in most cases, there are times when we want to save the cached state of a hidden element. Vue keep-alive helps in solving this problem. It can also increase your application speed and improve your application user experience.

In this article, I’m going to give an in-depth explanation of what a dynamic component is, and how to keep your components cached by using keep alive with a code example as well.

This article will cover the following:

  1. Introduction
  2. Installation and Setup
  3. Brief intro Dynamic Component
  4. What is Vue keep-alive?
  5. Why should I use Keep-Alive?
  6. Conclusion

 

Introduction to Vue Js

Vue.js is a progressive JavaScript framework for creating UIs (User Interfaces) and SPAs (Single Page Applications) (Single-page Applications). This framework is well-known for its quick learning curve. It’s such a simple and approachable library that we can start constructing web applications in Vue.js with just a basic understanding of HTML, CSS, and JavaScript.

Installation and Setup

The following method explains how to build up your project and install Vue JavaScript. Let’s go on installing Vue Js or you can get a starter project Github  as we won’t be using any libraries in our application. 

First, create a new Vue project with the following command:

vue create shopping-list

You can select the Vue options manually

Finally, our project is ready.

We will use a simple shopping list item for a code example, But before we get started, let’s understand what a dynamic component is.

 

Brief intro to Vue Dynamic Component

Users can transition between two or more components without routing with Vue dynamic components, and they can even keep the data state when going back to the original component. The main concept is to allow users to dynamically mount and unmount components in the user interface without the usage of routers.

Enough of the talking let’s look at some code examples:

Example One
  • The first step is to  create a parent component called ShoppingList, which has two child components, OldItem, and NewItem.
  • The OldItem will contain the list of shopping items, while the NewItem will have an input.
OldItem.vue
<template>
  <div class="flex flex-col mt-8">
    <div class="-my-2 py-2 overflow-x-auto sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8">
      <div
        class="
          align-middle
          inline-block
          shadow
          overflow-hidden
          sm:rounded-lg
          border-b border-gray-200">
        <table class="min-w-full">
          <thead>
            <tr>
              <th
                class="
                  px-6
                  py-3
                  border-b border-gray-200
                  bg-gray-50
                  text-left text-xs
                  leading-4
                  font-medium
                  text-gray-500
                  uppercase
                  tracking-wider
                "
              >
                Category
              </th>
              <th
                class="
                  px-6
                  py-3
                  border-b border-gray-200
                  bg-gray-50
                  text-left text-xs
                  leading-4
                  font-medium
text-gray-500
                  uppercase
                  tracking-wider
                "
              >
                List Item
              </th>
              <th
                class="
                  px-6
                  py-3
                  border-b border-gray-200
                  bg-gray-50
                  text-left text-xs
                  leading-4
                  font-medium
                  text-gray-500
                  uppercase
                  tracking-wider
                "
              >
                Date
              </th>
              <th
                class="
                  px-6
                  py-3
                  border-b border-gray-200
                  bg-gray-50
                  text-left text-xs
                  leading-4
                  font-medium
                  text-gray-500
                  uppercase
                  tracking-wider
                "
              >
                Quantity
              </th>
             
            </tr>
          </thead>
          <tbody
            class=""
            v-for="(list, index) in lists"
            :key="index"
          >
            <tr>
              <td
                class="
                  px-6
                  py-4
                  whitespace-nowrap
                  border-b border-gray-200
                  items-center
                "
              >
                 {{ list.cat }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap border-b border-gray-200">
                {{ list.text }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap border-b border-gray-200">
                <!-- <div class="text-sm leading-5 text-gray-900"> -->
                {{ list.date }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap border-b border-gray-200">
                {{ list.quantity }}
              </td>
              
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "OldItem",
  data() {
    return {
      lists: [
        {
          cat: "Food",
          text: "Bag of rice",
          quantity: "2",
          date: "09/09/21",
          checked: false,
        },
        {
          cat: "Tech",
          text: "Surface Laptop 2",
          quantity: "2",
          date: "09/09/21",
          checked: false,
        },
        {
          cat: "School",
          text: "Drawing Board",
          quantity: "2",
          date: "09/09/21",
          checked: false,
        },
      ],
     
    };
  },
 
};
</script>

 

NewItem.vue
<template>
  <div class="Employee">
    <form action="">
      <input type="text" placeholder="New List" class="input-bg p-4 my-4">
    </form>
  </div>
</template>
<script>
export default {
  name: "NewItem",
 
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.input-bg{
  background-color:#F9F5FF;
  outline:#F9F5FF ;
  border:2px solid rgb(197, 194, 194)
}
</style>

Here’s an output of what the application should look like:

Vue Keep-Alive Output

Please note to understand the purpose of the Keep-alive component, we will have to implement a dynamic component without Keep-alive.

 

How does Dynamic Component work?

To grasp the concept of keep-alive, you must first comprehend what dynamic components are. In a nutshell, it can use the v-bind:is directive to swap between distinct components.

Example Two

In the next step, we create a single button inside of our template in our parent component. Which loops through the listed item, and displays the item with a key of a tab.

Next, we add a click event with the value of the tab.

<template>
  <div id="app">
    <h1 class="text-3xl bold py-3">ShoppingList</h1>
    <div>
      <button
        v-for="tab in tabContents"
        :key="tab"
        @click="component = tab"
        class="btn-item"
      >
        {{ tab }}
      </button>
    </div>
   
  </div>
</template>


The next step is to implement our dynamic component. Please note when working with the dynamic component, we have to use the component Element.

<div>
<component />
</div>

and then we can determine exactly what component is rendering in the element  by using the v-bind:is directive

<component :is="component" />

Next, we add the tab to our component property

component:"OldItem"

In the above code example, I used the OldItem as my default tab because that’s my first child component which has the listed item we can choose to use any one.

<template>
  <div id="app">
    <h1 class="text-3xl bold py-3">ShoppingList</h1>
    <div>
      <button
        v-for="tab in tabContents"
        :key="tab"
        @click="component = tab"
        class="btn-item"
      >
        {{ tab }}
      </button>
    </div>
   
  </div>
</template>
<script>
import OldItem from "./components/OldItem.vue";
import NewItem from "./components/NewItem.vue";
export default {
  name: "App",
  components: {
    OldItem,
    NewItem,
  },
  data() {
    return {
      tabContents: ["OldItem", "NewItem"],
      component: "OldItem",
    };
  },
};
</script>

 

Output

Vue Keep-Alive Output

In the above output we noticed that when we go to a new component in the above code example, vue produces a new instance of our component, which simply means that when we click on oldlist, it creates a new instance of that tab, and when we click on newlist, it makes a new instance of that tab.

 

Brief intro to Vue Keep-Alive

When we move between various components dynamically, the Vue keep-alive component allows us to keep the current component’s state by caching it. It also speeds up rendering because they’re cached.

Now, let’s look at a quick code example to understand it better:

In this example, we use the keep-alive component to wrap the dynamic component

<Keep-alive>
    <component :is="component" />
</Keep-alive>

Vue Keep-alive is a wrapper that changes the default  functionality of our element; it stores the cached version of a dynamic component when it’s not active which means with Keep-alive  vue does not create new component instances.

 

Output

Vue Keep-Alive Output

In the output seen above. We discovered that the keep-alive component saved a cached version of our component, so anytime we enter a value into our input and navigate to the next tab or the previous tab, our value is still saved.

 

Why should I use Vue Keep-Alive?

  • When your component isn’t active, it saves a cached reference to it.
  • It’s really simple to save state and switch between dynamic components quickly.
  • Keep-alive is beneficial since it provides us with unique lifecycle hooks.

 

Conclusion

An abstract element is the name of the component. It doesn’t show up as a component and doesn’t render a DOM element. Keep-alive components can be used for anything that requires existing data to be kept on the screen. It can be used to save user input in forms or the results of API calls. Hopefully, this article has given you a good understanding on what the Keep-alive component is and how to cache your dynamic component.


I am a software developer with development experience in frontend building responsive website sites using these web technologies like Javascript, VueJs, HTML and CSS, Bootstrap Tailwind CSS. I specialize in converting designs to Code, and I love teaching and sharing my technical ideas through an article.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *