什么是keep-alive
keep-alive 组件是vue的一个内置组件。
作用是当路由或者组件切换时,他会缓存住包裹在其中的组件或者页面的状态,而不是销毁掉,这样下次重新进入被包裹的路由页面时不会重新渲染dom而是从缓存中读取。
<template>
<div class="layout" ref="layout">
<top-info></top-info>
<top-nav></top-nav>
<div class="minBox">
<keep-alive>
<router-view v-if="$route.meta.keepAlive" class="routerView" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" class="routerView" />
</div>
<Footer v-show="!$route.meta.hideFooter"></Footer>
</div>
</template>
/*router.js*/
const routes = [{
path: "/",
name: "layout",
redirect: "/home",
children: [{
path: "fiProductBx",
name: "fiProductBx",
component: () =>
import ("../views/fiProductBx/fiProductBx.vue"),
meta: {
keepAlive: true
}
},{
path: "fiProductBxDetail",
name: "fiProductBxDetail",
component: () =>
import ("../views/fiProductBx/fiProductBxDetail.vue"),
}]
}]
注意:
使用keep-alive时需要注意,keep-alive提供了两个新的生命周期钩子函数:
(1)activated:这个函数是用来替代created函数,当组件第一次渲染时或者每次keep-alive重新激活时都会被调用,要注意的是,组件第一次渲染时生命周期执行顺序是created-> mounted-> activated,之后keep-alive重新激活不在执行 created与mounted,只执行 activated。
(2)deactivated:当每次离开组件时这个函数会被调用,需要注意的是,如果有需要离开路由时进行相应的逻辑,正常的话会写在beforeRouteLeave函数中,但实际项目中会遇到beforeRouteLeave无法执行的情况,建议在deactivated也进行一些判断。
beforeRouteLeave(to, from, next) {
if (to.name == "serverdetails") {
from.meta.keepAlive = true;
} else {
from.meta.keepAlive = false;
}
next();
}