nuxt-anchorscroll
這個模組提供滾動實作 (滾動至頂部和滾動至錨點元素)。最初它是為了錨點滾動而設計,這就是為什麼它被稱為 nuxt-anchorscroll
功能
- 開箱即用配置
- 支援兩種佈局*
- 可擴展
開箱即用配置
- 對於滾動至頂部 - 立即滾動,直到頂部且偏移量為零,忽略 x 軸
- 對於錨點滾動 - 平滑滾動,直到頂部元素且偏移量為零,忽略 x 軸
- 表面 -
html
和body
元素 - 通用功能 - 如果元素存在則滾動至錨點 (使用
route.hash
作為選擇器),否則滾動至頂部 - 遵循頁面 metanuxt-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) ?? {},
},
}
}
}
})
此外,您的 matched 函數可以為滾動指定不同的表面。
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
或透過 nuxi module
安裝
npx nuxi@latest module add nuxt-anchorscroll
- 將
nuxt-anchorscroll
新增至nuxt.config.ts
的modules
區段
export default defineNuxtConfig({
modules: [
'nuxt-anchorscroll',
]
})
- 此外,如果您正在使用 transitions,您可能也希望在不同的 hook 上滾動
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>