Nuxt.js 3 和现场锚点导航

vin*_*est 6 anchor vue.js nuxt.js nuxtjs3

我正在学习 Nuxt.js 3,并正在编写一个简单的项目,该项目采用单滚动设计,其中有一个带有锚链接的菜单。单击链接,站点应自动滚动到锚点(如带有 id 的 div)。为了测试这一点,我设置了一个简单的 Nuxt 3 安装npx nuxi init nuxt-app,删除了演示内容并将其替换为:

pages/index.vue

<template>
  <div>
    <div id="home"><p>hello world</p></div>
    <div class="menu">
      <nuxt-link :to="{ path: '/', hash: '#ciao' }">
        link
      </nuxt-link>
    </div>
    <div style="height: 3000px">placeholder</div>
    <div id="ciao"><p>ciao world</p></div>
    <div class="menu">
      <nuxt-link :to="{ path: '/', hash: '#home' }">
        link
      </nuxt-link>
    </div>
    <div style="height: 3000px">placeholder</div>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

问题是,它不起作用。点击浏览器中的 url 更改为localhost:3000/#ciao或。localhost:3000/#home但这种观点并没有改变。

我还需要在 nuxt 中设置其他东西才能使锚点导航正常工作吗?

kis*_*ssu 8

As answered here: https://github.com/nuxt/framework/discussions/5561#discussioncomment-3007717

Using a regular a tag solves the issue

<a href="/#ciao">
  go to ciao's hash
</a>
Run Code Online (Sandbox Code Playgroud)

Otherwise, you can also use

<nuxt-link :to="{ hash: '#home' }" :external="true"> <!-- no need for a path if same page -->
  go to home's hash
</nuxt-link>
Run Code Online (Sandbox Code Playgroud)

The external prop (Nuxt3 only) is detailed here: https://v3.nuxtjs.org/api/components/nuxt-link#props

Quote from the documentation

Forces the link to be considered as external (true) or internal (false). This is helpful to handle edge-cases.