vue中的缓存——keep-alive,activated,deactivated

1、通过keep-alive和router-view实现路由缓存,具体代码如下:
在app.vue:

<router-view v-if="!$route.meta.keepAlive"/>
<keep-alive>
<router-view v-if="$route.meta.keepAlive"/>
</keep-alive>
在路由文件中配置相关参数,来判断该路由是否需要缓存,当keepAlive存在并且值为true时,缓存该路由

{
path: 'dCustomerPage',
name: '客户管理',
component: dCustomerPage,
meta:{
keepAlive: true,
}
},
2、关于activated钩子函数
首次进入该路由的页面时会触发created,mounted,activated等钩子函数,但使用this.router.go1返回该路由的时候,不会触发created和mounted,只会触发activated。如果调用this.router.go(−1)返回该路由的时候,不会触发created和mounted,只会触发activated。如果调用this.router.go(-1)返回该路由后希望手动刷新数据,可以在activated(){}中执行相关的请求,但首次进入或者f5刷新界面的时候会多次触发相关数据请求,可以用定时器解决或者类似锁的操作。

3、关于deactivated钩子函数
在离开该缓存路由后,该路由的组件并没有被销毁,如果需要销毁如定时器相关的操作可以在deactivated钩子函数中处理,类似于beforeDestroy钩子函数的调用

猜你喜欢

转载自www.cnblogs.com/wtsx-2019/p/12762542.html