作用:
vue内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM
keep-alive是用在一个直属子组件被开关的情形,同时只有一个子组件在渲染,若有v-for则不会工作
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello,
meta: {
keepAlive: false
}
},
{
path: '/page1',
name: 'Page1',
component: Page1,
meta: {
keepAlive: true
}
}
]
})
属性:
include: 字符串或正则表达式,只有名称匹配的组件会被缓存
exclude: 字符串或正则表达式,名称匹配的组件不会被缓存》
max: 数字,最多可以缓存多少组件实例
<keep-aliveinclude="a,b">
<component:is="view"></component>
</keep-alive>
<keep-alive:include="/a|b/">
<component:is="view"></component>
</keep-alive>
<keep-alive:include="['a','b']">
<component:is="view"></component>
</keep-alive>
生命周期:
activated和deactivated会在keep-alive树内所有嵌套的组件中触发
如:B页面是缓存页面
当A页面跳到B页面时,B页面的生命周期:activated(可在此时更新数据)
B页面跳出时,触发deactivated
B页面自身刷新时,会触发created-mouted-activated
{
path:'/',
name:'A',
component:A,
meta:{keepAlive:true}}
exportdefault{
data(){return{};},
methods:{},
beforeRouteLeave(to,from,next){
to.meta.keepAlive=true;
next()}}
exportdefault{
data(){return{};},
methods:{},
beforeRouteLeave(to,from,next){
to.meta.keepAlive=false;next()}}