vue实现keepalive
Vue 中实现 keep-alive
在 Vue 中,keep-alive 是一个内置组件,用于缓存动态组件或组件的状态,避免重复渲染和销毁。以下是实现 keep-alive 的几种方法:
基本用法
将需要缓存的组件包裹在 keep-alive 标签内:
<template>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
</template>
结合路由使用
在 Vue Router 中,可以通过 keep-alive 缓存路由组件:
<template>
<keep-alive>
<router-view></router-view>
</keep-alive>
</template>
缓存特定组件
通过 include 或 exclude 属性指定需要缓存或排除的组件:
<template>
<keep-alive include="ComponentA,ComponentB">
<component :is="currentComponent"></component>
</keep-alive>
</template>
动态缓存
使用 v-bind 动态绑定 include 或 exclude:
<template>
<keep-alive :include="cachedComponents">
<component :is="currentComponent"></component>
</keep-alive>
</template>
<script>
export default {
data() {
return {
cachedComponents: ['ComponentA', 'ComponentB']
}
}
}
</script>
生命周期钩子
被缓存的组件会触发 activated 和 deactivated 生命周期钩子:
export default {
activated() {
console.log('组件被激活');
},
deactivated() {
console.log('组件被停用');
}
}
结合路由元信息
通过路由的 meta 字段控制缓存:
const routes = [
{
path: '/a',
component: ComponentA,
meta: { keepAlive: true }
},
{
path: '/b',
component: ComponentB,
meta: { keepAlive: false }
}
];
在模板中动态判断:
<template>
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</template>
缓存的最大实例数
通过 max 属性限制缓存的最大组件实例数:
<template>
<keep-alive :max="5">
<component :is="currentComponent"></component>
</keep-alive>
</template>
注意事项
keep-alive仅适用于直接子组件,不适用于嵌套组件。- 被缓存的组件会保留状态,但不会重新触发
created或mounted钩子。 - 使用
include或exclude时,组件需要设置name选项。







