Single Page Applications Chapter 15
To accomplish this, let's modify our router code to the following:
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/', component: Home },
{ path: '/sports', component: Sports },
{ path: '/fashion', component: Fashion }
],
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { x: 0, y: 0 }
}
}
})
We added a line that specifies the new mode to be history (no hash in the link) and we
defined the scrollBehavior function to go back to the last position if present; if it's a new
page, it should scroll to the top-left corner.
You can try this by refreshing the browser and going back to the home page.
Open the sports page and click on the link in the middle of the page. The new page now
displays from the beginning.
Click on back and the savedPosition gets restored.
Note how the URL looks much nicer now: