Sometimes, we want to create anchor tags with Vue Router.
In this article, we’ll look at how to create anchor tags with Vue Router.
How to create anchor tags with Vue Router?
To create anchor tags with Vue Router, we can add the scrollBehavior
method when we create the VueRouter
instance.
For instance, we write
new VueRouter({
mode: "history",
scrollBehavior: (to, from, savedPosition) => {
if (to.hash) {
return { selector: to.hash };
} else {
return { x: 0, y: 0 };
}
},
routes: [
{ path: "/", component: AbcView },
//...
],
});
to create the VueRouter
instance with an object that has the scrollBehavior
method.
In it, we check for the hash with to.hash
.
If it’s set, then we return { selector: to.hash }
to scroll to the element with the ID given by the hash.
Otherwise, we don’t scroll.
Conclusion
To create anchor tags with Vue Router, we can add the scrollBehavior
method when we create the VueRouter
instance.