SoFunction
Updated on 2025-04-13

Implementation steps for Vue3 dynamically using KeepAlive components

Overview

In Vue 3 projects, we sometimes need to routemetaInformation to dynamically determine whether to use itKeepAliveComponents to control the cache behavior of components. This article will explain in detail how to implement this function.

Implementation steps

1. Modify the RouterView component

First, we need to modifyRouterViewcomponents, so as tometaInformation to determine whether to use itKeepAlive

<template>
  <RouterView #default="{ Component, route }">
    <component :is="getWrapperComponent()">
      <component :is="Component" />
    </component>
  </RouterView>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";

const getWrapperComponent = (keepAlive: boolean) => {
  return keepAlive ? "KeepAlive" : "div";
};
</script>

In this example, we define agetWrapperComponentFunction, according tokeepAliveThe value of  returnKeepAliveordivComponents.

2. Make sure the routing is configured correctly

Make sure your routing configuration containsinformation:

// 
export const routes = [
  {
    path: "/",
    name: "Home",
    component: () => import("@/views/"),
    meta: { title: "Home", keepAlive: true },
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("@/views/"),
        meta: { title: "Dashboard", keepAlive: true },
        children: [
          {
            path: "stats",
            name: "Stats",
            component: () => import("@/views/"),
            meta: { title: "Stats", keepAlive: true },
            children: [
              {
                path: "details",
                name: "Details",
                component: () => import("@/views/"),
                meta: { title: "Details", keepAlive: false },
              },
            ],
          },
        ],
      },
    ],
  },
];

3. Use KeepAlive and RouterView

Use in main application componentsRouterViewand ensureKeepAliveCorrect import:

<template>
  <RouterView #default="{ Component, route }">
    <component :is="getWrapperComponent()">
      <component :is="Component" />
    </component>
  </RouterView>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";

const getWrapperComponent = (keepAlive: boolean) => {
  return keepAlive ? "KeepAlive" : "div";
};
</script>

4. Make sure KeepAlive is imported correctly

Ensure correct import in the projectKeepAliveComponents:

import { KeepAlive } from "vue";

This is the article about the implementation steps of Vue3 dynamically using KeepAlive components. For more related content related to Vue3 dynamically using KeepAlive, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!