【发布时间】:2019-08-31 03:12:44
【问题描述】:
我在我的网站导航中使用 nuxt-links,其中大多数指向主页中的散列元素/锚点,例如:
<nuxt-link
v-else
class="text-link"
:to="localePath('index') + #hash"
>
如果当前在主页上,但当我导航到其他站点时,它会完成它的工作,例如。 /about 并单击导航栏 nuxt 链接(所以我想从 /about 导航到 /#hash 或 /any-other-site#hash)我收到一个 nuxt 错误,以检查显示“无法读取”的控制台属性 'offsetTop' 为 null"。
我在 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(以便滚动到该锚点?)
【问题讨论】:
-
如果您使用的是 nuxt 2.4+ 版本,那么 this 是您应该设置滚动行为的方式,特别是底部的 return Promise 部分。
-
@Andrew1325 使用默认配置(您提到的那个),当我单击 mu nuxt 链接
<nuxt-link to="/#hash">时,滚动到该元素永远不会发生。点击不会触发任何事情。
标签: javascript vue.js vue-router nuxt.js