vue记录滚动位置
1.问:有一个图片列表页(类似某宝),点击任何一个进去之后再返回,返回到刚刚访问的位置,一个很常见的需求。
2.尝试过原生js,利用scrollTop和localStorage结合,点击的时候记录scrollTop值;也试过vue-route的scrollBehavior,都没奏效
3.我用的是vue单页面应用
js方法代码如下:
var map = {};
window.onhashchange = function() {
document.body.scrollTop = 0;
}
window.onscroll = function() {
if (document.body.scrollTop) {
// 存
map[location.hash] = document.body.scrollTop;
} else {
var timer = null;
timer = setInterval(function(){
if (document.body.scrollTop == map[location.hash]) {
clearInterval(timer);
} else {
document.body.scrollTop = map[location.hash];
}
}, 20);
}
}
vue scrollBehavior方法代码如下:
if (savedPosition) {
// savedPosition is only available for popstate navigations.
return savedPosition
} else {
const position = {}
// new navigation.
// scroll to anchor by returning the selector
if (to.hash) {
position.selector = to.hash
// specify offset of the element
if (to.hash === '#eg') {
position.offset = { y: 100 }
}
}
// check if any matched route config has meta that requires scrolling to top
if (to.matched.some(m => m.meta.scrollToTop)) {
// cords will be used if no selector is provided,
// or if the selector didn't match any element.
position.x = 0
position.y = 500
}
// if the returned position is falsy or an empty object,
// will retain current scroll position.
return position
}