router.js
// routerhistory
const appRouter = {
mode: "history",
routes: [
{
path: "/list",
name: "list",
component: List,
meta: {
keepAlive: true //
}
}
]
}
add keep-alive to the App.vue entry file
<template>
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
< H2 > I remember that the above can be realized, if not, then add the following to try how I realized it < / H2 >
router.js main code (can also be put into main.js)
import { getScrollTop, setScrollTop } from "@/utils/mixin";
let routerList = [];
router.beforeEach((to, from, next) => {
//
let position = getScrollTop();
let currentRouterIndex = routerList.findIndex(e => {
return e.path === from.fullPath;
});
if (currentRouterIndex != -1) {
routerList[currentRouterIndex].position = position;
} else {
routerList.push({
path: from.fullPath,
position: position
});
}
});
router.afterEach((to, from, next) => {
let savedPosition = routerList.find(e => {
return e.path === to.fullPath;
});
if (typeof savedPosition !== "undefined") {
Vue.nextTick(() => {
setScrollTop(savedPosition.position);
});
} else {
Vue.nextTick(() => {
setScrollTop(0);
});
}
});
utils/mixin.js
/**/
export function getScrollTop() {
return (
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop
);
}
/**/
export function setScrollTop(value) {
window.scrollTo(0, value);
}
save a sessionStorage as the identifier of the location of the list page before entering the details page, and take this session when initializing the list page.
what does it mean that I can't remember the location? You can remember the location when you leave using either sessionStorage or vuex. When you come in, take this position in the requested callback, and then scroll to the corresponding location.
the solution is mainly to record the location. The above several people have made it very clear. If you use vue-router, you can put the record location in meta
1, and when the page leaves
.
beforeRouteLeave (to, from, next) {
//
let position = document.getElementById('vux_view_box_body').scrollTop
if (to.path === '/home') {
from.meta.position = 0
} else {
from.meta.position = position
}
next()
}
2. Go back to the current page and scrollTo (0, position) after $nextTick or setTimeout in mounted
read the article that it should be OK to use keep-alive, but I haven't used it either.