How to create anchor tags with Vue Router
I believe you are asking about jumping directly to a particular area of page, by navigating to an anchor tag like #section-3
within the page.
For this to work, you need to modify your scrollBehavior function as follows:
new VueRouter({
mode: 'history',
scrollBehavior: function(to, from, savedPosition) {
if (to.hash) {
return {selector: to.hash}
//Or for Vue 3:
//return {el: to.hash}
} else {
return { x: 0, y: 0 }
}
},
routes: [
{path: '/', component: abcView},
// your routes
]
});
Ref: https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling
I attempted creating a jsFiddle example but it is not working because of mode:'history'
. If you copy the code and run locally, you will see how it works: https://jsfiddle.net/mani04/gucLhzaL/
By returning {selector: to.hash}
(or {el: to.hash}
in Vue 3) in scrollBehavior, you will pass the anchor tag hash to the next route, which will navigate to the relevant section (marked using id
) in that route.
For me the {selector: to.hash}
solution just refused to work with vue-router 4.0.0. The following approach worked and also enabled smooth scrolling.
The timeout of 500ms is there to allow the page to load, because I found that otherwise smooth scrolling would not scroll to the correct position (because the page was still loading).
const scrollBehavior = (to, from, savedPosition) => {
if (to.hash) {
setTimeout(() => {
const element = document.getElementById(to.hash.replace(/#/, ''))
if (element && element.scrollIntoView) {
element.scrollIntoView({block: 'end', behavior: 'smooth'})
}
}, 500)
//NOTE: This doesn't work for Vue 3
//return {selector: to.hash}
//This does
return {el: to.hash};
}
else if (savedPosition) {
return savedPosition
}
return {top: 0}
}