My navigation from a side menu to a specific link on the main page is not working with ion-router-link
and scrollBehavior
router/index.js
const routes = [
...
{
path: "/books",
component: Books,
},
{
path: "/books/:key",
component: () => import("../views/BooksDetails.vue"),
},
];
...
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return { el: to.hash, left: 0, top: 64 };
}
},
Link <router-link :to="`/books/${selectedBook}#${chapter.key}`"> Jump to chapter </router-link>
Target
<div :id="chapter.key">
Output of to
"fullPath": "/books/myBook1#chapter1",
"hash": "#chapter1",
"query": {},
"path": "/books/myBook1",
"params": { "key": "myBook1" },
"matched": [
{
"path": "/books/:key",
"meta": {},
"props": { "default": false },
"children": [],
"instances": { "default": {} },
"leaveGuards": {},
"updateGuards": {},
"enterCallbacks": {},
"components": {
"default": {
"props": {},
"__file": "BooksDetails.vue",
"__hmrId": "42539a20"
}
}
}
],
"meta": {},
"href": "/books/myBook1#chapter1"
}
CodePudding user response:
I was able to solve this by the answer from @Masoud Ehteshami to the similar question.
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
scrollBehavior(to, from, SavedPosition) {
if (to.hash) {
const el = window.location.href.split("#")[1];
if (el.length) {
document.getElementById(el).scrollIntoView({ behavior: "smooth" });
}
} else if (SavedPosition) {
return SavedPosition;
} else {
document.getElementById("app").scrollIntoView({ behavior: "smooth" });
}
},
});