Ensure to verify the support of history.pushState
in the browser being tested. It is also important to log the savedPosition
as no scrolling will take place if the values are falsy. When initializing the router instance, you have the option to provide the scrollBehavior
function as shown below:
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
}
})
The scrollBehavior
function takes in the to and from route objects. The third argument, savedPosition
, is only accessible during a popstate
navigation (activated by the browser's back/forward buttons).
This function can return a scroll position object either in the format:
{ x: number, y: number }
//or
{ selector: string, offset? : { x: number, y: number }} //offset only supported in 2.6.0+
If a falsy value or an empty object is returned, scrolling will not occur.
Please note that this functionality is dependent on the browser supporting history.pushState
If desired, you can save the current scroll offset before navigating. Here is a way to achieve it:
const container = document.querySelector('.container')
let scrollOffset = {x: container.scrollTop, y: container.scrollLeft}
Subsequently, store the scrollOffset
prior to routing so that when the savedPosition
is falsy, this object can be utilized.