I'm using Vue Router and scrollBehavior and each route still loads a the top of the page (0,0), rather than remembering my scroll position. Thoughts on what I'm missing?
Here's my router code:
const scrollBehavior = (to, from, savedPosition) => {
if (savedPosition) {
return savedPosition;
} else {
return { x: 0, y: 0 };
}
};
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
scrollBehavior,
});
Adding dynamic routes in VueUpdate the router/index. js file with the new route in the routes array. Remember to include the import for the Post component. Restart your app and head to localhost:8080/post/dynamic-routing in your browser.
If you're using Vue Router you'll push the new URL onto the router in order to do a redirect: this. $router. push('www.yoursite.com/blog') .
Which of the following methods of Vue router can be invoked to return to the previous page? push . This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.
Have you checked for history.pushState
support in the browser you are testing? Also, log the savedPosition
because no scrolling will happen if the values are falsy. When creating the router instance, you can provide the scrollBehavior
function as given,
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
}
})
The scrollBehavior
function receives the to and from route objects. The third argument, savedPosition
, is only available if this is a popstate
navigation (triggered by the browser's back/forward buttons).
The function can return a scroll position object. The object could be in the form of:
{ 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, no scrolling will happen.
Note: this feature only works if the browser supports
history.pushState
If you want, You can store the current scroll offset before navigating. Here is how you can do it.
const container = document.querySelector('.container')
let scrollOffset = {x: container.scrollTop, y: container.scrollLeft}
Now, store the scrollOffset
before routing, when the savedPosition
is falsy, You can use this object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With