Vue 的 keep-alive 的作用是什么
keep-alive
可以在组件切换时,保存其包裹的组件的状态,使其不被销毁,防止多次渲染。其拥有两个独立的生命周期钩子函数 actived 和 deactived,使用keep-alive
包裹的组件在切换时不会被销毁,而是缓存到内存中并执行 deactived 钩子函数,命中缓存渲染后会执行 actived 钩子函数。
props
- include - 字符串或正则表达,只有匹配的组件会被缓存
- exclude - 字符串或正则表达式,任何匹配的组件都不会被缓存
-
// 组件 a
-
export default {
-
name: 'a',
-
data () {
-
return {}
-
}
-
}
-
<keep-alive include="a">
-
<component>
-
<!-- name 为 a 的组件将被缓存! -->
-
</component>
-
</keep-alive>可以保留它的状态或避免重新渲染
-
<keep-alive exclude="a">
-
<component>
-
<!-- 除了 name 为 a 的组件都将被缓存! -->
-
</component>
-
</keep-alive>可以保留它的状态或避免重新渲染
但实际项目中,需要配合vue-router共同使用
App.vue
-
<template>
-
<div id="app">
-
<!-- 路由占位符 -->
-
<!-- <router-view></router-view> -->
-
<keep-alive>
-
<router-view v-if="$route.meta.keepAlive">
-
<!-- 这里是会被缓存的视图组件 -->
-
</router-view>
-
</keep-alive>
-
-
<router-view v-if="!$route.meta.keepAlive">
-
<!-- 这里是不被缓存的视图组件 -->
-
</router-view>
-
</div>
-
</template>
router -> index.js
-
const routes = [
-
{ path: '/', redirect: '/index' },
-
{ path: '/', redirect: '/home' },
-
{
-
path: '/home',
-
component: HomeLayout,
-
children: [
-
{
-
path: '/home',
-
component: Home
-
},
-
{
-
path: '/workingCondition',
-
component: () =>
-
import(
-
/*webpackChunkName:"workingCondition"*/ '../views/workingCondition/index.vue'
-
),
-
meta: {
-
keepAlive: true // 需要被缓存
-
}
-
}
-
]
-
},
-
{
-
path: '/reportView',
-
component: () => import('../views/other/reportView.vue')
-
},
-
{
-
path: '/todo',
-
component: () => import(/*webpackChunkName:"ToDo"*/ '../views/ToDo.vue'),
-
meta: {
-
keepAlive: true // 需要被缓存
-
}
-
}
-
]
转:https://blog.csdn.net/qq_37548296/article/details/110798890