vue路由如何实现缓存
Vue 路由实现缓存的方法
使用 <keep-alive> 组件
通过 Vue 内置的 <keep-alive> 组件包裹 <router-view>,可以缓存匹配的组件实例。需配合路由配置的 meta 字段或组件 name 属性控制缓存规则。
<template>
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
</template>
路由配置示例:
{
path: '/detail',
component: Detail,
meta: { keepAlive: true } // 启用缓存
}
动态控制缓存
通过 include 或 exclude 属性指定需要缓存的组件名(需与组件 name 选项一致):

<keep-alive :include="['ComponentA', 'ComponentB']">
<router-view />
</keep-alive>
结合路由钩子管理状态
在 activated 和 deactivated 生命周期钩子中处理组件激活/停用时的逻辑:
export default {
activated() {
// 恢复滚动位置或重新请求数据
},
deactivated() {
// 保存当前状态
}
}
嵌套路由的缓存

嵌套路由需确保外层 <keep-alive> 能匹配到子路由的组件名:
<keep-alive :include="['ParentComponent']">
<router-view />
</keep-alive>
强制刷新缓存组件
通过修改 :key 或使用 this.$destroy() 强制销毁组件实例:
// 方法1:修改 router-view 的 key
<router-view :key="$route.fullPath" />
// 方法2:在组件内调用
this.$destroy()
注意事项
- 被缓存的组件会跳过
created和mounted钩子,但会触发activated。 - 大量缓存可能导致内存占用过高,需合理设置
include/exclude。 - 动态路由参数变化时,默认会复用组件实例,可通过
watch: $route或:key触发更新。






