Skip to content

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

属性类型默认值说明
itemsNavItem[][]导航数据源,{ id: string, title: string }
active-id / v-model:active-idstring''当前激活的菜单项 id
offset-topnumber0滚动偏移量,预留给固定导航栏

Emits

事件参数说明
update:active-idid: stringv-model 更新事件
click-itemid: string点击菜单项时触发

Slots

插槽说明
default需要监听滚动的内容区域