keep-alive
包裹动态组件时可对该组件进行缓存。
props
include:字符串或正则表达式,匹配的组件将被缓存。
exclude:与include相反
<keep-alive>
<component></component> //缓存component
</keep-alive>
<keep-alive include='a'> //缓存name为a的组件
<component></component>
</keep-alive>
<keep-alive include='a,b'> //缓存name为a或b的组件
<component></component>
</keep-alive>
<keep-alive :include='/a|b/'> //缓存name为a或b的组件,正则需要bind
<component></component>
</keep-alive>
<keep-alive>
<router-view></router-view> //缓存所有页面
</keep-alive>
结合router使用
<keep-alive>
<router-view v-if='$route.meta.keeyAlive'></router-view>
</keep-alive>
<keep-alive>
<router-view v-if='$route.meta.keeyAlive'></router-view>
</keep-alive>
routes:[
{
path:'/index',
name:'index',
component:index,
meta:{
keepAlive:true //需要缓存
}
}
]
动态设置
需要在路由的beforeRouteLeave(to,from,next)钩子函数中设置
有三个页面:A,B,C。当B跳到A时A缓存,当C跳到A时A不缓存。
B:
export default{
beforeRouteLeave(to,from,next){
to.meta.keepAlive=true; //B到A时A不用刷新
}
}
c:
export default{
beforeRouteLeave(to,from,next){
to.meta.keepAlive=false; //C到A时A会刷新
}
}