Reputation: 4035
I'm trying to use a NuxtLink to scroll to an anchor tag. From the docs I see I need to create this file app/router.scrollBehavior.js
and place my code there.
For example, this works. It scrolls 500px in the y axis, but what I really want is to scroll to the hash.
export default function (to, from, savedPosition) {
if (to.hash) {
return { x: 0, y: 500 }
}
}
Events Page
<div
v-for="(event, i) in events"
:id="event.id"
:ref="event.id"
:key="i"
>
</div>
Navigation Component
<NuxtLink
v-for="item in items"
:key="`item.id"
:to="item.href"
>
{{ item.name }}
</NuxtLink>
I haven't been able to make it scroll to the hash. I tried several options an none of them seems to work. For example:
Does not work (I also tested with selector instead of el)
export default function (to, from, savedPosition) {
if (to.hash) {
return {
el: to.hash,
behavior: 'smooth',
}
}
}
Does not work
export default function (to, from, savedPosition) {
return new Promise((resolve, reject) => {
if (to.hash) {
setTimeout(() => {
resolve({
el: to.hash,
behavior: 'smooth',
})
}, 500)
}
})
}
Any ideas about what it could be the problem?
Upvotes: 1
Views: 759
Reputation: 4035
Ok, so finally this is what worked for me. I had to install Vue-Scroll and inside app/router.scrollBehavior.js
import Vue from 'vue'
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)
export default function (to, from, savedPosition) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (to.hash) {
VueScrollTo.scrollTo(to.hash, 300, { easing: 'linear', offset: -60 })
}
}, 500)
})
}
I used this answer as a reference How to smoothly scroll to an element via a hash in Nuxt? but I had to change the setTimeOut
time from 10ms to 500ms because it wasn't working properly on my static page.
Upvotes: 2