复制了官方示例中的scrollBehavior方法

const scrollBehavior = (to, from, savedPosition) => {
  console.log(savedPosition);
  if (savedPosition) {
    // savedPosition is only available for popstate navigations.
    return savedPosition;
  }
  const position = {};
  // new navigation.
  // scroll to anchor by returning the selector
  if (to.hash) {
    position.selector = to.hash;
  }
  // 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 = 0;
  }
  // if the returned position is falsy or an empty object,
  // will retain current scroll position.
  return position;
};

根据官方文档,后退时应该会获得savedPosition,并自动跳转回之前的位置,我这里console.log(savedPosition)有输出位置,但没有跳转过去

我反复试验,得到的结果是,
在没有加keep-alive的前提下,
打开A页面,向下滚动一定距离,进入B页面,此时若B页面高度较高,超出了浏览器高度,即有滚动条的情况下,后退回A,A是能保持滚动位置的,但若B页面没有滚动条,则后退回A,A也滚回顶部,此时console.log(savedPosition)是有位置的,

但这应该不是正确的实践吧?

 

出處

另外的參考

scrollBehavior (to, from, savedPosition) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (savedPosition) {
                    resolve(savedPosition)
                } else {
                    resolve({ x: 0, y: 0 })
                }
            }, 500)
        })
}
Logo

前往低代码交流专区

更多推荐