【问题标题】:Vue.js, how to scroll to an anchor via ID without navigating to a routeVue.js,如何通过 ID 滚动到锚点而不导航到路由
【发布时间】:2021-05-18 16:52:53
【问题描述】:

我有 Vue + vue-router 用于浏览应用程序中的页面,但我还需要能够在没有路由的情况下移动到 ID/Anchor。目前,路由器总是激活并更改 URL 到具有 ID 名称的新页面,而不是移动到同一页面上的 ID。

<a href="#example">link</a>

路线设置:

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior (to) {
    if (to.hash) {
      return {
        selector: to.hash
      }
    }
  }
})

点击链接时,页面会滚动到 ID,然后会转到不存在的页面 http://localhost:8080/#/example

我真的不知道如何使用锚/ID 而不被 vue-router 劫持。

【问题讨论】:

  • 我会尝试使用beforeEach 导航守卫,检查您的路线集合,确定它尝试导航到的路线不是有效路线,如果不是,请在守卫内调用next(false)
  • @dexygen 我在vue-router docs 中找到了导航守卫,它成功了一半!它确实阻止路由到空白页面,但是尽管文档说它会阻止它,但它仍然会更改 url:“并且可以选择返回以下任何值:- false:取消当前导航。如果浏览器 URL 已更改(由用户手动或通过后退按钮),它将被重置为 from 路线。”我的 beforeEach:router.beforeEach((to,from) =&gt; { if (!to.matched.length) return false }})
  • 最糟糕的是你可以使用 history/push-state 来恢复 URL,但你会认为有更好的方法
  • 我的另一个想法是找到使用 createWebHashHistory() 的替代方法,因为锚点本身会将哈希值放在 URL 中

标签: javascript vue.js scroll vue-router anchor


【解决方案1】:

如果您在同一页面上,您可以创建一个方法并使用window.scrollTo

这是一个示例函数:

scrollToContent() {
      window.scrollTo(
        0,
        document.getElementById("content").getBoundingClientRect().y +
          window.scrollY -
          120
      );
    },

【讨论】:

  • 这不会阻止路由,滚动本身目前工作它只是路由。
猜你喜欢
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多