When it comes to my website navigation, I rely on nuxt-links a lot. Most of these links direct users to specific sections within the home page using hashes like:
<nuxt-link
v-else
class="text-link"
:to="localePath('index') + #hash"
>
Everything works fine when I'm on the home page itself. However, things get tricky when I try to navigate from another page, such as /about, and click on a navbar nuxt-link. This results in a nuxt error message displaying "Cannot read property 'offsetTop' of null".
To make sure scrolling to anchored elements works even within the same site, I have configured my router in nuxt.config as follows:
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' });
}
},
I've tried various methods like 'hash' or '#hash' in the :to attribute, but nothing seems to work. Can someone please guide me on how to successfully navigate to a different page along with scrolling to a specific anchor?