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) ?? {},
},
}
}
}
})
您的匹配函式還可以指定不同的捲動表面。
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',
]
})
- 此外,如果您正在使用過渡效果,您可能也希望在不同的 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
composable 來實現
// 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>