0

我从侧边菜单导航到主页上特定链接的导航不起作用, ion-router-link并且scrollBehavior

路由器/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 };
    }
  },

关联 <router-link :to="`/books/${selectedBook}#${chapter.key}`"> Jump to chapter </router-link>

目标 <div :id="chapter.key">

的输出 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"
}
4

1 回答 1

0

我能够通过@Masoud Ehteshami 对类似问题的回答解决这个问题

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" });
    }
  },
});
于 2022-02-20T23:19:00.297 回答