我在我的网站导航中使用 nuxt-links,其中大部分指向主页中的散列元素/锚点,例如:
<nuxt-link
v-else
class="text-link"
:to="localePath('index') + #hash"
>
如果当前在主页上但当我导航到另一个站点时它会完成它的工作,例如。 /about 然后我点击一个导航栏 nuxt-link(所以我想从 /about 导航到 /#hash 或 /any-other-site#hash)属性 ‘offsetTop’ 为空”。
我在 nuxt.config 中的路由器配置(没有它我什至无法滚动到与元素位于同一站点的锚定元素!):
router: {
scrollBehavior(to) {
if (to.hash) {
return window.scrollTo({ top: document.querySelector(to.hash).offsetTop + window.innerHeight, behavior: 'smooth' });
}
return window.scrollTo({ top: 0, behavior: 'smooth' });
}
},
在 :to 属性中,我尝试了 ‘hash’ ‘#hash’,但没有任何效果。可以请任何人帮助我吗?如何导航到不同的页面 + #anchor(以便滚动到该锚点?)
原文由 shikinen 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您使用的是
Nuxt-Link
,在这里遇到此问题的任何人都是一个简单的解决方案而不是使用不起作用的
<nuxt-link to="#contact" >Contact</nuxt-link>
。使用<nuxt-link :to="{ path: '/',hash:'#contact'}">Contact</nuxt-link>
path
是您将导航到的页面hash
是你要滚动到的位置希望这对某人有帮助。