I am looking for a smart way to handle anchors on a page using Vue Router. Consider the following:
<router-link to="#app">Apply Now</router-link>
<div id="app">...</div>
The “scroll to anchor” behavior described in the documentation works fine, except for:
- When you click on the anchor, it leads you to
div id="app". Now scroll from divback to anchor and try clicking it again - this time you will not jump down to div. In fact, the anchor will save the class router-link-active, and the URL will still contain a hash /#app; - Using the steps above, if you refresh the page (the URL will still have a hash) and click on the anchor, nothing will happen.
This is very unfortunate from a UX point of view, because the potential customer must manually scroll all the way down again to get to the application section.
I was wondering if Vue Router covers this situation. For reference, here is my router:
export default new VueRouter({
routes,
mode: 'history',
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return { selector: to.hash }
} else if (savedPosition) {
return savedPosition;
} else {
return { x: 0, y: 0 }
}
}
})
source
share