Keep-alive multi-level route cache problem

1. Problem description

In the reconciliation center, when the last two convenient navigation menus are the same module and level 3 or above, the two convenient tabs can be cached normally when they are switched normally, but when the last TAB is deleted, the other TAB page is no longer cached.

2. Cause analysis

Keep-alive supports two levels of cache by default, and invalidates the cache of pages at levels 3 and above. The previous handling method is as follows: After the route changes are monitored, the current route identifier and its parent identifier are saved together. When multiple pages exist, close one of the pages, and delete the parent identifier and the parent identifier together. At this time, the array has no parent identifier and the cache of other pages of the same level becomes invalid.

3. Solution

All the routes in the routing configuration table are divided into two operations. One is to keep the routes as they are for display in the menu, and the other is to flatten the routing configuration table and process all the routes into level-two routes. In this way, keep-Alive can support caching by default.

4. Process

  • Get the complete routing configuration

    const modules = []
    files.keys().forEach(key => {
        const filesObj = files(key).default || files(key)
        Object.keys(filesObj).forEach(keyOne => {
            modules.push(filesObj[keyOne])
        })
    })
    Copy the code
  • The route configuration is complete

    export const menuList = modules; // a flattening menu const routerList = formatTwoStageRoutes(formatTwoStageRoutes(modules)); Const router = new VueRouter({scrollBehavior: () => ({y: 0}), mode: 'history', base: Process.env.base_url, routes: routerList, // Use flattened route in route configuration})Copy the code
  • Flattening method

    export const formatFlatteningRoutes =(routesList => { if (routesList.length <= 0) return routesList; let list = []; RoutesList. ForEach (v => {if(v.path === '/') {// Add a preliminary layout and a home page. list = list.concat(formatFlatteningRoutes(v.children)) } else if (v.children && v.children.length > 0) { list = list.concat(formatFlatteningRoutes(v.children)) } else { list.push(v); } }) return list; }) export const formatTwoStageRoutes = list => { if (list.length <= 0) return list; const routerList = []; list.forEach(v => { if (v.path === '/') { routerList.push({ component: v.component, name: v.name, path: v.path, redirect: v.redirect, meta: v.meta, children: []})} else if (Valerie plame ath = = = '/ login' | | Valerie plame ath = = = '/ showcasePage') {/ / no need to configure the layout of the page routerList. Push (v)} else { routerList[0].children.push({ ... v }) } }) return routerList; }Copy the code