【问题标题】:Scrolling to anchors with Vue Router使用 Vue Router 滚动到锚点
【发布时间】:2020-12-05 00:41:16
【问题描述】:

我需要在 vuejs 中设置一个锚链接才能转到:

<h1 id="apply">Test anchor</h1>

以下方法有效,但将 url 更改为 http://localhost:8080/#/apply

<a href="#apply" class="btn btn-primary mt-3">Apply Now</a>

如果我刷新页面,它不知道该去哪里。

以下内容对我也不起作用。它甚至没有下拉到#apply。

<router-link to="/careers/job-1#apply">test</router-link>

如何使用 vuejs 路由设置锚链接?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-router


    【解决方案1】:

    pathhash 属性添加到您的to 对象:

    <router-link :to="{ path: '/careers/job-1', hash: '#apply' }">test</router-link>
    

    并将scrollBehavior 添加到您的路由器定义中:

    const router = new VueRouter({
      ...
      scrollBehavior (to, from, savedPosition) {
        if (to.hash) {
          return {
            selector: to.hash,
            behavior: 'smooth'
          };
        }
        return { x: 0, y: 0 };  // Go to the top of the page if no hash
      },
      ...
    })
    

    现在它应该滚动(平滑,除非您删除 behavior 属性)到哈希定义的锚点

    【讨论】:

    • 是的,linter 在抱怨。我已经删除了它。效果很好!谢谢!
    • 一个问题。如果我单击按钮使其滚动。然后我手动向上滚动并再次单击它不会锚定下来。你找到解决这个问题的方法了吗?
    • 这是一个很好的问题,没有我所知道的内置解决方案。您可以尝试其中一种解决方案herethis 也是一个使用/扩展的好主意
    猜你喜欢
    • 2020-08-22
    • 2021-03-20
    • 2017-12-10
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2014-12-08
    相关资源
    最近更新 更多