SoFunction
Updated on 2025-03-03

Solve the problem of scrollTop after vue single page routing jump

As a junior user of vue, there are too many pitfalls encountered during the development process. When looking at the page, I found the problem of page scrolling. When a page scrolls and clicks the route on the page to adjust it to the next page, the page that jumps also scrolls, and the scroll bar is not at the top of the page.

At the beginning, I used a very stupid method, adding (0,0); to each page to solve the problem, but this is too cumbersome. Finally, I discussed it with my friends and added this code to the page

(function (to) {
 (0, 0)
})

There will be no scrolling problem after the route jumps.

But this approach is unfriendly, we can use scrollBehavior (to, from, savedPosition) {} to solve the problem.

When we write the route, as follows

import Vue from 'vue'
import Router from 'vue-router'
(Router);
 
(Router)
 
export default new Router({
 routes: [
 {
  path: '/',
  name: 'HelloWorld',
  component: resolve => require(['../components/'],resolve)
 }
 ],
 scrollBehavior (to, from, savedPosition) {
 if (savedPosition) {
  return savedPosition
 } else {
  return { x: 0, y: 0 }
 }
 }
})

The scrollBehavior method receives to and from routing objects. The third parameter savedPosition is available if and only if the popstate navigation (triggered through the browser's Forward/Back button). There are many kinds of it to use, you can try it.

The above article solves the problem of scrollTop after single page routing jump is all the content I share with you. I hope it can give you a reference and I hope you can support me more.