Scrolling behavior

The history mode of the router allows us to manage the page scrolling when a route changes. We can reset the position to the top every time, or restore the position the user was in before changing the route (this is very useful when they go back in the browser).

When creating the router instance, we can pass a scrollBehavior function that will get three arguments:

  • to is the target route object.
  • from is the previous route object.
  • savedPosition is the scroll position that has been automatically saved for each entry in the browser history. Each new entry will not have this until the route changes.

The scrollBehavior function expects an object that can take two different forms. The first is the coordinate of the scroll we want to apply; for example:

{ x: 100, y: 200 }

The second one is a selector of the HTML element we want the page to scroll to, with an optional offset:

{ selector: '#foo', offset: { x: 0, y: 200 } }
  1. So to scroll to the top of the page when the route changes, we need to write this:
      const router = new VueRouter({
routes,
mode: 'history',
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
},
})

To scroll to the <h1> element each time, we could do this:

return { selector: 'h1' }
  1. Instead, we will check if the route has a hash to mimic the browser behavior:
      if (to.hash) {
return { selector: to.hash }
}
return { x: 0, y: 0 }
  1. Finally, we can restore the scroll position if there is any:
      if (savedPosition) {
return savedPosition
}
if (to.hash) {
return { selector: to.hash }
}
return { x: 0, y: 0 }

It's that simple! The app now should behave like an old multi-page website. You can then customize the way the scroll behaves with offset or route meta properties.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.115.195