nuxt-anchorscroll
此模块提供滚动实现(滚动到顶部和滚动到锚点元素)。最初它是为锚点滚动而设计的,这就是为什么它被称为 nuxt-anchorscroll
特性
- 开箱即用配置
- 支持两种布局*
- 可扩展
开箱即用配置
- 对于顶部滚动 - 立即滚动,直到顶部且偏移为零,忽略
x
轴 - 对于锚点滚动 - 平滑滚动,直到顶部元素且偏移为零,忽略
x
轴 - 作用表面 -
html
和body
元素 - 通用功能 - 如果元素存在则滚动到锚点(使用
route.hash
作为选择器),否则滚动到顶部 - 遵循页面 metanuxt-anchorscroll
选项
支持两种布局*
通常情况下,你使用裁剪后的 html 或完整的 html。在第一种情况下(你可以现在检查),滚动到锚点将不起作用。如果是这样,你可以进行最小化设置。
但是,如果锚点滚动由浏览器处理,则需要额外的设置 - 完整的解释在模块 playground 中。
可扩展
锚点滚动可以通过 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',
],
},
})
- 此外,如果你使用标准布局,请查看 playground 解释。
就是这样!你现在可以在你的 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>