在Vue构建的单页面应用(SPA)中,路由模块一般使用vue-router。vue-router不保存被切换组件的状态,它进行push或者replace时,旧组件会被销毁,而新组件会被新建,走一遍完整的生命周期。
**但有时候,我们有一些需求,比如跳转到详情页面时,需要保持列表页的滚动条的深度,等返回的时候依然在这个位置,或者填写表单时,跳转到下一页在返回时,需要保存刚才表单填写的状态,**这样可以提高用户体验。在Vue中,对于这种“页面缓存”的需求,我们可以使用keep-alive组件来解决这个需求。
keep-alive是个抽象组件(或称为功能型组件),实际上不会被渲染在DOM树中。它的作用是在内存中缓存组件(不让组件销毁),等到下次再渲染的时候,还会保持其中的所有状态,并且会触发activated钩子函数。因为缓存的需要通常出现在页面切换时,所以常与router-view一起出现
// App.vue
<div class="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
const router = new VueRouter({
routes: [
{
path: '/',
name: 'index',
component: () => import('@/components/index'),
meta: {
title: '众安保修'
}
},
{
path: '/list',
name: 'list',
component: () => import('@/components/zan/contract/list/index'),
meta: {
auth: needAuth,
title: '列表',
keepAlive: true
}
},
]
})
当keepAlive === true 时 ,会被缓存起来。
如果只想渲染某一些页面/组件,可以使用keep-alive组件的include/exclude属性。include属性表示要缓存的组件名(即组件定义时的name属性),接收的类型为string、RegExp或string数组;exclude属性有着相反的作用,匹配到的组件不会被缓存。假如可能出现在同一router-view的N个页面中,我只想缓存列表页和详情页,那么可以这样写:
上面include的写法不是常用的,因为它固定了哪几个页面缓存或不缓存,假如有下面这个场景:
现有页面:首页(A)、列表页(B)、详情页(C),一般可以从:A->B->C;
B到C再返回B时,B要保持列表滚动的距离;
B返回A再进入B时,B不需要保持状态,是全新的。
很明显,这个例子中,B是“条件缓存”的,C->B时保持缓存,A->B时放弃缓存。其实解决方案也不难,只需要将B动态地从include数组中增加/删除就行了。具体步骤是:
// store文件夹/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
keepAliveComponents: []
},
mutations
})
// store文件夹/mutations.js
const mutations = {
keepAlive (state, component){
// 注:防止重复添加(当然也可以使用Set)
!state.keepAliveComponents.includes(component) && state.keepAliveComponents.push(component)
},
noKeepAlive (state, component) {
const index = state.keepAliveComponents.indexOf(component)
index !== -1 && state.keepAliveComponents.splice(index, 1)
}
}
export default mutations
// app.vue
<template>
<div id="app">
<keep-alive :include="keepAliveComponent">
<router-view/>
</keep-alive>
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
name: 'app',
created(){
},
computed: {
...mapState({
keepAliveComponent: state => state.keepAliveComponents
})
}
}
</script>
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: '/',
name: 'index',
component: () => import('@/components/index'),
meta: {
title: '首页'
}
},
{
path: '/list',
name: 'list',
component: () => import('@/components/zan/contract/list/index'),
meta: {
title: '列表',
keepAlive: true
}
}
]
})
// 在跳转之前执行
router.beforeEach((to, from, next) =>{
// 在路由全局钩子beforeEach中,根据keepAlive属性,统一设置页面的缓存性
// 作用是每次进入该组件,就将它缓存
if (to.meta.keepAlive) {
store.commit('keepAlive', to.name)
}
next()
})
export default router
// B页面
export default {
name: 'B',
created () {
},
beforeRouteLeave (to, from, next) {
// 如果下一个页面不是详情页(C),则取消列表页(B)的缓存
if (to.name !== 'C页面name') {
this.$store.commit('noKeepAlive', from.name)
}
next()
}
}
因为B的条件缓存,是B自己的职责,所以最好把该业务逻辑写在B的内部,而不是A中,这样不至于让组件之间的跳转关系变得混乱
一个需要注意的细节:因为keep-alive组件的include数组操作的对象是组件名、而不是路由名,因此我们定义每一个组件时,都要显式声明name属性,否则缓存不起作用。而且,一个显式的name对Vue devtools有提示作用。
import store from './store'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '' ,
components: {App}
})