Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Router save scroll position on a route and go back to that position when navigating back?

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,
});
like image 835
Kirk Ross Avatar asked Aug 17 '20 22:08

Kirk Ross


People also ask

How do I create a dynamic route Vue?

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.

How do I redirect a page in Vue?

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?

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.


1 Answers

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.

like image 117
Kiran Maniya Avatar answered Oct 20 '22 23:10

Kiran Maniya