项目报错:
项目背景:Vue3项目
"vue": "^3.4.29",
"vue-router": "^4.0.13"
问题代码:
<transition name="fade-transform" mode="out-in">
<keep-alive>
<router-view />
</keep-alive>
</transition>
原因:
Vue Router更新至4.0版本后,移除了直接在
<transition>
或<keep-alive>
组件内部使用<router-view>
的能力。引入了一系列的变化和改进,其中包括对<router-view>
组件使用方式的调整。在Vue Router 4中,直接在
<transition>
或<keep-alive>
组件内使用<router-view>
不再被推荐,因为这可能导致组件的生命周期钩子不按预期工作。
所以,有了新的写法:
<router-view v-slot="{ Component }">
<transition name="fade-transform" mode="out-in">
<div>
<keep-alive>
<component :is="Component"/>
</keep-alive>
</div>
</transition>
</router-view>
那我就很好奇了, 其中的Component是如何获取的呢?
他的解释是这样的,
v-slot="{ Component }"
:通过作用域插槽获取由<router-view>
解析出的当前组件实例。<component :is="Component" />
:使用动态组件特性,根据Component
变量的值渲染对应的组件。
当然此时此刻,keepAlive的固定使用include,exclude,max使用还是老方法。
踩个小坑,进个小步,加油!