0

I've set up a front-end environment with Vue.js, Vite, and Vue Router.

When I navigate between pages, the scroll position is remembered, causing the new page to start at the previous location instead of the top. The expected behavior is for navigation (not using the back button) to always begin at the top of the new page. The back button functionality, where it remembers the previous scroll position, works correctly.

I've tried using the scrollBehavior option in Vue Router, but it doesn't seem to be working as expected.

Here's the code I've used for the router configuration:

const router = createRouter({
  history: createWebHistory(),
  routes: [
    // My routes here
  ],
  scrollBehavior(to, from, savedPosition) {
    // This is the part that doesn't seem to have any effect.
    // I want to always scroll to the top on new navigation.
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

I've also checked the documentation and other online resources, but I can't figure out why this isn't working.

1 Answer 1

0

scrollBehavior only controls the window/document scroll. If your app layout scrolls inside a div (e.g. a wrapper like #content with overflow: auto; height: 100vh; to keep a fixed header), Vue Router can’t move that internal scroller. The browser will still remember scroll for back/forward, so “back remembers position” works, but “forward go to top” doesn’t.

  1. Remove the custom scroll container and allow the page itself to scroll. Then your current code will work:
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition
    return { top: 0, left: 0 }          // always start at top on new route
  }
})

!!! Make sure you don’t have CSS that traps scroll on a child !!!

@) Or 2 option, if you must keep a scrollable content area, move it to top in scrollBehavior yourself:

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition       // back/forward

    // Manually scroll your container
    const scroller = document.querySelector('#content'); // your scrollable div
    if (scroller) scroller.scrollTo({ top: 0, left: 0, behavior: 'auto' });

    return false;  // tell Vue Router we handled scrolling
  }
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.