vue 切换路由页面时,滚动条滚动到最上面

vue项目里,使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。 vue-router 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。

第一种方法:
可以参考vue官方写法:
https://router.vuejs.org/zh/guide/advanced/scroll-behavior.html

第二种方法:
可以在路由的导航守卫afterEach里面添加:window.scrollTo(0,0);
在这里插入图片描述
第三种方法: (本人用得方法)
const router = new VueRouter({
/mode: ‘history 或 hash’,/
mode: ‘history’,
scrollBehavior: () => ({ y: 0 }), //滚动到顶端
routes: constRoutes
});

猜你喜欢

转载自blog.csdn.net/xingchen678/article/details/128723182