Scroll with anchor support for Nuxt
npm install nuxt-anchorscrollnuxt-anchorscroll
x axis
x axis
html and body elements
route.hash as selector),
nuxt-anchorscroll options
matched field of NuxtApp.$anchorScroll
script setup)
ts
nuxtApp.$anchorScroll!.matched.push(({ path, hash }) => {
// Exit when route is not represent fixed example
if (!path.startsWith('/standard/fixed'))
return undefined
if (hash) {
// All anchor element on this route is mangled
const targetSelector = #fixed-${hash.slice(1)}
const targetElement = document.querySelector(targetSelector)
if (targetElement) {
return {
toAnchor: {
target: targetElement as HTMLElement,
scrollOptions: toValue(useNuxtApp().$anchorScroll?.defaults?.toAnchor) ?? {},
},
}
}
}
})
`
Also your matched function can specify different surfaces for scrolling.
`ts
nuxtApp.$anchorScroll!.matched.push(({ path, hash }) => {
// Exit when route is not represent fixed example
if (!path.startsWith('/scrollable'))
return undefined
const surfaces = [...document.querySelectorAll('#exited-scrollable-surface')]
return {
toAnchor: {
surfaces,
scrollOptions: {
/ ... /
},
},
toTop: {
surfaces,
scrollOptions: {
/ ... /
},
}
}
})
`
Quick Setup
1. Add nuxt-anchorscroll dependency to your project
Use your favorite package manager (I prefer yarn)
`bash
yarn add -D nuxt-anchorscroll
pnpm add -D nuxt-anchorscroll
npm install --save-dev nuxt-anchorscroll
`
Or install it via nuxi module
`bash
npx nuxi@latest module add nuxt-anchorscroll
`
2. Add nuxt-anchorscroll to the modules section of nuxt.config.ts
`ts
export default defineNuxtConfig({
modules: [
'nuxt-anchorscroll',
]
})
`
3. Additionally, if you are using transitions, probably you also want to scroll on different hook
`ts
export default defineNuxtConfig({
modules: [
'nuxt-anchorscroll',
],
anchorscroll: {
hooks: [
// Or any valid hook if needed
// Default is page:finish
'page:transition:finish',
],
},
})
`
4. Additionally, if you using standard layout, see playground explanation.
That's it! You can now use nuxt-anchorscroll in your Nuxt app ✨
Composable
Most probably that you want to scroll to anchor ro to top on click. That's possible via useAnchorScroll composable
`ts
// Default to top is instant
const { scrollToAnchor, scrollToTop } = useAnchorScroll({
toTop: {
scrollOptions: {
behavior: 'smooth',
offsetTop: 0,
}
},
})
`
And use it in template
`html
class="box"
mt-12
flex flex-row gap-4 align-baseline
>
:id="id"
text-3xl font-extrabold
>
:href="#${id}"
mb-a mt-a
text-xl
@click="scrollToAnchor(id)"
>
#