My goal is to implement scrolling to an anchor using scrollBehavior in VueJS.
Typically, I update the current router as follows:
this.$router.push({path: 'componentName', name: 'componentName', hash: "#" + this.jumpToSearchField})
This is how my VueRouter is set up:
const router = new VueRouter({
routes: routes,
base: '/base/',
mode: 'history',
scrollBehavior: function(to, from, savedPosition) {
let position = {}
if (to.hash) {
position = {
selector : to.hash
};
} else {
position = {x : 0 , y : 0}
}
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(position)
}, 10)
})
}
});
My routes are defined as:
[
{
path: '/settings/:settingsId',
component: Settings,
children: [
{
path: '',
name: 'general',
components: {
default: General,
summary: Summary
}
},
{
path: 'tab1',
name: 'tab1',
components: {
default: tab1,
summary: Summary
}
},
{
path: 'tab2',
name: 'tab2',
components: {
default: tab2,
summary: Summary
}
},
{
path: 'tab3',
name: 'tab3',
components: {
default: tab3,
summary: Summary
}
}
]
},
{
path: '/*',
component: Invalid
}
];
For example, if I am on the tab1 component and want to navigate to the anchor 'test' on the tab3 component.
After calling router.push()
, I observe that scrollBehavior
is triggered, causing the component to switch from tab1 to tab3 and the URL to change accordingly (e.g. from http://localhost:8080/tab1 to http://localhost:8080/tab3#test), but the window position remains at the top instead of where the anchor is placed.
It's worth noting that there is a textarea with id="test" on the tab3 component.
What could be causing this issue?