gitakachan / vue-project-collections-and-issues

vue issues
0 stars 0 forks source link

scrollbehavior + html bookmark 滾動到#hash #14

Open gitakachan opened 3 years ago

gitakachan commented 3 years ago

參考:https://codesandbox.io/s/vuerouter-4-anchor-links-vc73l?file=/src/views/About.vue

//router/index.js
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    if (to.hash) {
      return { el: to.hash, behavior: "smooth" }; //behavior: "smooth" 使平滑滾動
    }
    return { x: 0, y: 0 };
  },
});
//router link
<router-link
  to="/store/about/#vn"
  @click="collapse"
  class="nav-link"
  href="#"
  >關於</router-link
>

<!--滾動目標設定id-->
 <h1 id="vn">vn intro</h1>