I am creating a small Vue webapp, I want to create an anchor tag in this.
I have given an id to one of the div I wanted to have anchor tags
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
return {selector: to.hash}
}
else if (savedPosition) {
return savedPosition
}
return {top: 0}
}