keep-alive 缓存机制
需求简介:
客户需求点击二级页面跳转的时候,返回一级页面要能看到缓存得所有数据包括查询条件,页面页数等等...
解决方法:
我解决方法 vue中keepAlive的使用 缓存机制
一、vue中keepAlive的使用
首先介绍一下include和exclude vue文档 https://cn.vuejs.org/v2/api/#keep-alive
是在vue2.0以后新增的属性
include是需要缓存的组件;
exclude是除了某些组件都缓存; include 和 exclude 属性允许组件有条件地缓存。二者都可以
activated 与 deactivated。
简单介绍一下在被keep-alive包含的组件/路由中,会多出两个生命周期的钩子:activated 与 deactivated。
文档:在 2.2.0 及其更高版本中,activated 和 deactivated 将会在 树内的所有嵌套组件中触发。
activated在组件第一次渲染时会被调用,之后在每次缓存组件被激活时调用。
activated调用时机:
第一次进入缓存路由/组件,在mounted后面,beforeRouteEnter守卫传给 next 的回调函数之前调用:
beforeMount=> 如果你是从别的路由/组件进来(组件销毁destroyed/或离开缓存deactivated)=>mounted=> activated 进入缓存组件 => 执行 beforeRouteEnter回调
因为组件被缓存了,再次进入缓存路由/组件时,不会触发这些钩子:// beforeCreate created beforeMount mounted 都不会触发。
deactivated:组件被停用(离开路由)时调用
使用了keep-alive就不会调用beforeDestroy(组件销毁前钩子)和destroyed(组件销毁),因为组件没被销毁,被缓存起来了。
这个钩子可以看作beforeDestroy的替代,如果你缓存了组件,要在组件销毁的的时候做一些事情,你可以放在这个钩子里。
如果你离开了路由,会依次触发:
组件内的离开当前路由钩子beforeRouteLeave => 路由前置守卫 beforeEach =>全局后置钩子afterEach => deactivated 离开缓存组件 => activated 进入缓存组件(如果你进入的也是缓存路由
1、app或在需要缓存的router-view组件上包裹keep-alive组件
<keep-alive :include="cachedViews"> <router-view></router-view> </keep-alive>
export default { name: 'AppMain', computed: { cachedViews() { return this.$store.state.catch_components }, key() { return this.$route.path } } }
2、首先在路由中的meta标签中记录keepAlive的属性为true
path: '/classify', name: 'classify', component: () => import('@/views/classify/classify.vue'), meta: { title: '一级页面', keepAlive: true //true是缓存 } },
3、在store里加入需要缓存的的组件的变量名,和相应的方法
export default new Vuex.Store({ state: { catch_components:[] }, mutations:{ GET_CATCHE_COMPONENTS (state, data) { catch_components.push(data) } } })
4、在beforeRouteLeave钩子函数里控制需要缓存的组件
beforeRouteLeave (to, from, next) { //要在离开该组件的时候控制需要缓存的组件,否则将出现第一次不缓存的情况 if (vm.$route.meta.keepAlive) { // 去往二级详情页面跳转的时候,返回一级页面要能看到缓存得所有数据包括查询条件,页面页数等等... this.$store.commit('GET_CATCHE_COMPONENTS',vm.$route.name) } else { this.$store.commit('GET_CATCHE_COMPONENTS', []) } next() },