[英]nuxt-link: redirect to the same anchor with hash
I'm using a <nuxt-link>
component in my Nuxt application and I have the following problem:我在 Nuxt 应用程序中使用了
<nuxt-link>
组件,但遇到以下问题:
How could I overwrite this behavior so that when I click on the nuxt-link
, it scrolls to the desired section regardless of what I have clicked before ?我怎么能覆盖这种行为,以便当我点击
nuxt-link
,无论我之前点击了什么,它都会滚动到所需的部分? (Without refreshing the page) (不刷新页面)
Here is what my nuxt-link
looks like这是我的
nuxt-link
样子
<nuxt-link :to="{ path: localePath('/'), hash: '#homepage' }"
>
<span>Homepage</span>
</nuxt-link>
I believe that you should be able to add a click handler to your nuxt-link.我相信您应该能够向您的 nuxt-link 添加点击处理程序。
<nuxt-link
:to="{ path: localePath('/'), hash: '#homepage' }"
@click.native="scroll"
>
Homepage
</nuxt-link>
(not sure about the @click.native
, if that does not work just try @click
) (不确定
@click.native
,如果这不起作用,请尝试@click
)
And then within your methods:然后在你的方法中:
methods: {
scroll() {
// your scroll function, probably reading document.documentElement.scrollTop or similar
// if necessary check this.$route if the hash is already present, if so only do it in that case...
},
}
Hope that gives you a point to start?!希望这能给你一个起点?! Cheers
干杯
Got it to work with this function bound to a click.native
event as suggested by @Merc.按照
click.native
建议,让它与绑定到click.native
事件的这个函数一起使用。
handleScroll(anchorId: string): void {
if (this.$route.hash) {
const anchor = document.querySelector(`#${anchorId}`)
// Check if the anchor has been found
if (anchor) {
window.scrollTo({
// Scroll so that the anchor is at the top of the view
top: anchor.getBoundingClientRect().top + window.pageYOffset
})
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.