nuxt-anchorscroll
このモジュールは、スクロールの実装(ページトップとアンカー要素へのスクロール)を提供します。元々はアンカースクロールを目的としていたため、nuxt-anchorscroll
と呼ばれています。
機能
- すぐに使える設定済み
- 両方の種類のレイアウトに対応*
- 拡張可能
すぐに使える設定済み
- トップスクロールの場合 - オフセットゼロでトップまで瞬時にスクロール、
x
軸は無視 - アンカースクロールの場合 - オフセットゼロでトップ要素までスムーズにスクロール、
x
軸は無視 - 対象要素 -
html
およびbody
要素 - 一般的な機能 - 要素が存在する場合はアンカーにスクロール(セレクタとして
route.hash
を使用)、そうでない場合はトップにスクロール - ページメタのnuxt-anchorscroll
オプションを尊重
両方の種類のレイアウトに対応*
一般的なケースでは、切り取られたhtmlまたは完全なhtmlを使用します。最初のケース(今すぐ確認できます)では、アンカースクロールは機能しません。その場合は、最小限の設定を行うことができます。
しかし、アンカースクロールが(ブラウザによって)処理される場合、追加の設定が必要です - モジュールのプレイグラウンドで詳細な説明をご覧ください。
拡張可能
アンカースクロールは、NuxtApp.$anchorScroll
ランタイム設定の matched
フィールドを介して必要なルートに指定できます(デフォルト設定は script setup
の前に設定されます)
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) ?? {},
},
}
}
}
})
また、一致する関数は、スクロール用に異なる対象要素を指定できます。
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: {
/* ... */
},
}
}
})
クイックセットアップ
nuxt-anchorscroll
依存関係をプロジェクトに追加します
お好みのパッケージマネージャーを使用してください(yarnを推奨します)
yarn add -D nuxt-anchorscroll
pnpm add -D nuxt-anchorscroll
npm install --save-dev nuxt-anchorscroll
nuxt-anchorscroll
をnuxt.config.ts
のmodules
セクションに追加します
export default defineNuxtConfig({
modules: [
'nuxt-anchorscroll',
]
})
- さらに、トランジションを使用している場合は、おそらく別のフックでスクロールしたいと思うでしょう
export default defineNuxtConfig({
modules: [
'nuxt-anchorscroll',
],
anchorscroll: {
hooks: [
// Or any valid hook if needed
// Default is `page:finish`
'page:transition:finish',
],
},
})
- さらに、標準レイアウトを使用している場合は、プレイグラウンドの説明を参照してください。
これで完了です! Nuxtアプリで nuxt-anchorscroll
を使用できるようになりました ✨
コンポーザブル
おそらく、クリック時にアンカーまたはトップにスクロールしたいと思うでしょう。useAnchorScroll
コンポーザブルでそれが可能です
// Default to top is instant
const { scrollToAnchor, scrollToTop } = useAnchorScroll({
toTop: {
scrollOptions: {
behavior: 'smooth',
offsetTop: 0,
}
},
})
そして、テンプレートで使用します
<template>
<div
class="box"
mt-12
flex flex-row gap-4 align-baseline
>
<h2
:id="id"
text-3xl font-extrabold
>
<slot />
</h2>
<NuxtLink
:href="`#${id}`"
mb-a mt-a
text-xl
@click="scrollToAnchor(id)"
>
#
</NuxtLink>
</div>
</template>