Skip to content

WJ0527/keepAlive-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Vue 3 KeepAlive + 嵌套 RouterView Bug 复现

Bug 描述

当使用 <keep-alive> + <component :is="Component" :key="route.path" /> 模式缓存嵌套路由的中间组件 RouteView 时,从 Page1 切换到 Page2 后,DevTools 组件树中 被缓存(inactive)的 RouteView(key='/page1') 内部显示的子组件是 Page2,而不是预期的 Page1

组件结构

App
 └─ RouterView
     └─ Layout
         └─ Navbar
         └─ AppMain
             └─ Transition (BaseTransition)
                 └─ RouterView
                     └─ KeepAlive
                         ├─ RouteView key='/page2'  (active)
                         │   └─ RouterView
                         │       └─ Page2            ← 当前页面,正确
                         └─ RouteView key='/page1'  (inactive/cached)
                             └─ RouterView
                                 └─ Page2            ← BUG! 应该是 Page1

原因分析

AppMain 中通过 <component :is="Component" :key="key" /><keep-alive> 中缓存 RouteView。 但 RouteView 内部又有一个 <router-view>,它始终解析当前路由对应的组件。 当路由切换后,即使 RouteView 被 deactivated,其内部的 <router-view> 仍然指向当前路由的组件(Page2),而不是缓存时的组件(Page1)。

复现步骤

  1. npm install
  2. npm run dev
  3. 打开浏览器,安装 Vue DevTools
  4. 点击 "Page1" 链接,观察组件树
  5. 点击 "Page2" 链接
  6. 在 DevTools 组件树中查看 inactive 的 RouteView key='/page1'
  7. 其子组件显示 Page2 而非 Page1

涉及文件

  • src/components/layouts/AppMain.vue — KeepAlive + component :key 模式
  • src/components/layouts/RouteView.vue — 嵌套 router-view 中间层
  • src/router/index.js — 嵌套路由配置

About

a demo to reproduce vue3 keep-alive bug

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors