When using client-side routing, we may want to scroll to the top when navigating to a new route, or we may want to preserve the scrolling position of history entries, just like a real page reload does. ViewRouter allows you to achieve these, and even better, allows you to completely customize the scroll behavior on route navigation. on a smaller screen size than I've been using up until this point. If you click on a destination in the nav bar and then scroll down to the bottom of the page and then click on another destination, you will see that the page we navigate to is still scrolled to the bottom.
It would be a lot nicer if we could scroll the user back up to the top between each route. To do this, all that's needed is to add the scroll behavior function to our router options. Scroll behavior receives to and from. just like the navigation guards.
And on top of that, it gets a saved scroll position when we navigate through back and forward interactions. The saved position will result in a native-like behavior when navigating with back and forward buttons in the browser. We should return a scrollToOptions object from this function. that is, an object that can contain any of the following properties, top, left, and behavior.
For our use case, we want to return the saved position if it's available. For everything else, we'll just return a position of top zero. Now, when we switch between destinations, you see that the page jumps back up to the top. The scroll behavior and our transitions are conflicting a bit though, causing a weird jump to top before the transition occurs.
This is an easy fix. Remember, our transition is in the mode of out in. Each portion of that takes three hundred milliseconds to complete. We want to wait until the end portion of the transition to start to jump to the top of the page.
And so therefore, we can use a timeout to wait three hundred milliseconds before jumping to top. We can account for this in the scroll behavior function by returning a promise that resolves after three hundred milliseconds using setTimeout. There, that's better. If we wanted to, we can even give it a smooth scroll effect with the behavior property.
I think this is a little much for our case, but if other cases were to arise in the future, we could conditionally set the smooth behavior here based on anything we wanted to about the route where we're going.