ScrollSpy 滚动监听
ScrollSpy 组件通过 IntersectionObserver 监听内容区块的可见性,联动左侧导航高亮,支持点击平滑跳转和偏移量配置。
基础用法
滚动右侧内容区域,观察左侧导航高亮变化。
vue
<script setup>
const sections = Array.from({ length: 6 }, (_, i) => ({
id: `section-${i + 1}`,
title: `区块 ${i + 1}`,
}))
const activeId = ref('section-1')
</script>
<TScrollSpy :items="sections" v-model:active-id="activeId" :offset-top="20">
<div v-for="item in sections" :key="item.id" :id="item.id" style="min-height: 300px">
<h4>{{ item.title }}</h4>
<p>内容区域...</p>
</div>
</TScrollSpy>API
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
items | NavItem[] | [] | 导航数据源,{ id: string, title: string } |
active-id / v-model:active-id | string | '' | 当前激活的菜单项 id |
offset-top | number | 0 | 滚动偏移量,预留给固定导航栏 |
Emits
| 事件 | 参数 | 说明 |
|---|---|---|
update:active-id | id: string | v-model 更新事件 |
click-item | id: string | 点击菜单项时触发 |
Slots
| 插槽 | 说明 |
|---|---|
default | 需要监听滚动的内容区域 |