在setTimeout之后Vue.js滚动到新页面路由的顶部

Vue.js

番长路易

2020-03-16

当滚动到新路线顶部时,我的页面过渡效果不佳。我想等待100毫秒,然后它会自动滚动到顶部。以下代码根本不会滚动。有没有办法做到这一点?

export default new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'Home',
            component: Home
        }
    ],
    scrollBehavior (to, from, savedPosition) {
        setTimeout(() => {
            return { x: 0, y: 0 }
        }, 100);
    }
})

第1666篇《在setTimeout之后Vue.js滚动到新页面路由的顶部》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
小卤蛋梅蛋蛋 2020.03.16

当使用客户端路由时,我们可能希望在导航到新路由时滚动到顶部,或者像真实页面重新加载一样保留历史记录条目的滚动位置。通过vue-router,您可以实现这些目标,甚至更好,还可以完全自定义路线导航上的滚动行为。

注意:仅当浏览器支持时,此功能才可用 history.pushState

scrollBehavior (to, from, savedPosition) {
  return { x: 0, y: 0 }
}

具有保存的位置:

scrollBehavior (to, from, savedPosition) {
  if (savedPosition) {
    return savedPosition
  } else {
    return { x: 0, y: 0 }
  }
}

了解更多信息

前端猪猪GO 2020.03.16

其他答案无法处理一些极端情况,例如:

  1. 保存的位置 -当用户单击后退或前进位置时,将发生保存的位置。我们要保持用户正在查看的位置。
  2. 哈希链接 -例如,http://example.com/foo#bar要导航到一个页面上的元素idbar
  3. 最后,在所有其他情况下,我们都可以导航到页面顶部。

这是处理以上所有内容的示例代码:

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    } else if (to.hash) {
      return {
        selector: to.hash
      };
    } else {
      return { x: 0, y: 0 };
    }
  }
});
泡芙Green阳光 2020.03.16

如果您希望在每条路径上都发生这种情况,可以在路由器中的before 挂钩这样做

const router = new VueRouter({ ... })

router.beforeEach(function (to, from, next) { 
    setTimeout(() => {
        window.scrollTo(0, 0);
    }, 100);
    next();
});

如果您使用的是旧版本的vue-router,请使用:

router.beforeEach(function (transition) { 
    setTimeout(() => {
        window.scrollTo(0, 0);
    }, 100);
    transition.next();
});
番长路易 2020.03.16

这可能不是最好的方法,但是要添加

document.body.scrollTop = document.documentElement.scrollTop = 0;

在路由的核心组件(在本例中为Homemounted()函数中实现了我想要的。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android