首页 > 解决方案 > 直接访问 nuxt 应用程序中的 URL 时,初始页面加载时的滚动位置不会转到哈希/锚点位置

问题描述

我的 nuxt.js 应用程序中有一些锚链接。它工作正常。说,当我尝试通过具有 id 属性的 navbar/ 标签访问页面的一部分时,它工作正常。

<a href="#anchor">Scroll to anchor</a>- 这有效
<nuxt-link to="#anchor">Scroll to anchor</a>- 也有效

但是当我尝试通过 URL 直接访问相同的内容时 -xxx.com/test#anchor它需要进入测试页面但不会滚动到#anchor div。

我尝试过的几种解决方法是,

<nuxt-link :to="{path: '/', hash: 'anchor'}">link</nuxt-link>

我也在 nuxt-config 中更改了支持此功能的滚动行为,

scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
      return {
        selector: to.hash
      }
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  },

这在负载上不起作用。我发现已经提出了同样的问题,但仍然存在,

https://github.com/nuxt/nuxt.js/pull/6922

https://github.com/nuxt/nuxt.js/issues/6921

标签: javascriptnuxt.js

解决方案


有一个类似的问题,这个黑客解决了它。

  mounted() {
    if (this.$route.hash) {
      let hash = this.$route.hash
      hash = hash.replace('#', '')
      const anchor = document.getElementById(hash)

      if (anchor) {
        window.scrollTo({
          top: anchor.getBoundingClientRect().top + window.scrollY,
        })
      }
    }
  },


推荐阅读