回退保持&平滑滚动,在router文件中
const router = new VueRouter({
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return {
y: 0,
behavior: 'smooth'
}
}
}
})
如果顶部有固定导航栏点击跳转页面,要配合下面的方法,否则会经常滚动不到顶部
methods: {
pageJump(router, index) {
if (router === this.$route.path) {
this.scrollSmoothTo(0);
} else {
this.$router.push(router);
this.active = index;
this.scrollSmoothTo(0);
}
},
scrollSmoothTo(position) {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback, element) {
return setTimeout(callback, 17);
};
}
let scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
let step = function () {
let distance = position - scrollTop;
scrollTop = scrollTop + distance / 5;
if (Math.abs(distance) < 1) {
window.scrollTo(0, position);
} else {
window.scrollTo(0, scrollTop);
requestAnimationFrame(step);
}
};
step();
},
},