export const KeepaliveListMixin = { /** * 两个路由守卫 实现 从详情返回到列表 列表页面缓存 否则就不缓存 */ beforeRouteEnter (to, from, next) { to.meta.keepAlive = true; next() }, beforeRouteLeave (to, from, next) { if (to.name == "DetailStore") { //这里的路径是要跳转的需要缓存的路径 from.meta.keepAlive = true; } else { let Vnode = this.$vnode; let parentVnode = Vnode && Vnode.parent; if (parentVnode && parentVnode.componentInstance && parentVnode.componentInstance.cache) { var key = Vnode.key == null ? Vnode.componentOptions.Ctor.cid + (Vnode.componentOptions.tag ? `::${Vnode.componentOptions.tag}` : '') : Vnode.key; var cache = parentVnode.componentInstance.cache; var keys = parentVnode.componentInstance.keys; if (cache[key]) { this.$destroy(); if (keys.length) { var index = keys.indexOf(key); if (index > -1) { keys.splice(index, 1); } } cache[key] = null; } } } //记录离开时的位置 start let position = document.documentElement.scrollTop || document.body.scrollTop from.meta.savedPosition = position //记录离开时的位置 end next(); }, }
封装到KeepaliveListMixin.js里面 然后在你需要缓存的页面里面引入;
import { KeepaliveListMixin } from '@/mixins/KeepaliveListMixin'
mixins: [KeepaliveListMixin],
缓存浏览的位置 要配合 在router.js 配入以下代码
const scrollBehavior = function scrollBehavior (to, from, savedPosition) { // if (savedPosition) { //return savedPosition; // }else { // return { x: 0, y: 0 } //} //需要返回一个promise 否则滚动条的位置 和滚动条的值不一样 return new Promise((resolve) => { setTimeout(() => { if (savedPosition ) { return savedPosition }else { return { x: 0, y: 0 } } },0) }) }; const router = new Router({ routes, scrollBehavior, });
以上就能实现 keepalive 跳转到详情页面 返回的时候能缓存 且 记录浏览的位置; 从其他页面进入该页面就不会缓存