界面需要缓存常用场景:
商城主界面home.vue进入商品列表界面productList.vue,
点击商品查看详情需要给商品列表界面缓存,
若不缓存,从商品详情界面返回到商品列表界面会重新刷新商品列表数据,滚动位置就会被清除
- 路由配置界面需要缓存
{
path: '/home',
name: 'home',
component: () => import('@/views/home.vue')
}, {
path: '/productList',
name: 'productList',
component: () => import('@/views/productList.vue'),
meta: {
keepAlive: true // 需要被缓存
}
}, {
path: '/productDetail',
name: 'productDetail',
component: () => import('@/views/productDetail.vue')
}
- app.vue中使用keep-alive标签缓存界面
<keep-alive>
<router-view
v-if="$route.meta.keepAlive"
:key="$route.fullPath"
></router-view>
</keep-alive>
<router-view
v-if="!$route.meta.keepAlive"
:key="$route.fullPath"
></router-view>
- 清除缓存
商品列表进入详情会自动缓存,
但从商品列表返回到主页时需要清除缓存
beforeRouteLeave(to, from, next) { // 返回上一页清除缓存
if (to.path === '/home') {
let that = this
if (that.$vnode && that.$vnode.data.keepAlive) {
if (that.$vnode.parent && that.$vnode.parent.componentInstance && that.$vnode.parent.componentInstance.cache) {
if (that.$vnode.componentOptions) {
var key = that.$vnode.key == null
? that.$vnode.componentOptions.Ctor.cid + (that.$vnode.componentOptions.tag ? `::${that.$vnode.componentOptions.tag}` : '')
: that.$vnode.key
var cache = that.$vnode.parent.componentInstance.cache
var keys = that.$vnode.parent.componentInstance.keys
if (cache[key]) {
if (keys.length) {
var index = keys.indexOf(key)
if (index > -1) {
keys.splice(index, 1)
}
}
delete cache[key]
}
}
}
}
that.$destroy()
}
next()
}