百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
V

vue-use-active-scroll

> 前端框架
开源

突出 TOC/侧栏链接,不损失效果

99 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

突出 TOC/侧栏链接,不损失效果

Vue Use Active Scroll

Live Demo — Examples: With Template Refs - Nuxt Content Nested TOC

Why?

The Intersection Observer is a great API. But it may not be the one-size-fits-all solution to highlight TOC/sidebar links as it makes hard if not impossible to:

  • Highlight any clicked link even if it will never intersect
  • Always highlight first/last link once reached the top/bottom of the page
  • Get consistent results regardless of scroll speed
  • Immediately highlight links on click/hash navigation if smooth scrolling is enabled
  • Avoid unnatural highlighting with custom easings or smooth scrolling

Vue Use Active Scroll implements a custom scroll observer which automatically adapts to any type of scroll behavior and trigger and always returns the "correct" active target.

Do you really need it?

If you and your users don't care about the above gotchas, then no, please don't use this package because it adds a couple of unnecessary KBs to your bundle.

You can achieve an acceptable result with the Intersection Observer API as well. Alternatively, you can build an accurate scroll observer that acts similar to this package by looking at the SvelteKit Website's TOC source code in 100-150 lines of code.

Features

  • Precise and stable at any speed
  • CSS scroll-behavior or JS scroll agnostic
  • Adaptive behavior on mount, hash and prev/next navigation, scroll, click, cancel.
  • Customizable offsets for each scroll direction
  • Customizable offsets for first and last target
  • Customizable behavior on top/bottom reached
  • Supports custom scrolling containers
  • Supports both plain ids and template refs

What it doesn't do?

  • Scroll to targets
  • Mutate the DOM and inject styles
  • Require specific scroll behavior
  • Require or configure hash navigation

Getting Started

Installation

bash
pnpm add vue-use-active-scroll

# yarn add vue-use-active-scroll
# npm i vue-use-active-scroll
# bun add vue-use-active-scroll

[!WARNING] If you plan to use this package with scroll to anchors (e.g. docs TOC) and you're not using Nuxt, Vue Router is required and scrollBehavior must be configured in the router instance by following the next section.

Configure scrollBehavior

[!NOTE] If using Nuxt, you can skip to the next section as it's already taken care for you by the framework.

As explained in the above warning, Vue Router needs to be configured in order to scroll to anchors.

javascript
const router = createRouter({
   // Add this method 
   scrollBehavior(to) {
      if (to.hash) {
         return {
            el: to.hash,
         }
      }
   },
})

The above is the bare minimum required to get started and it will make sure that when clicking on a RouterLink that has an anchor in its href the window will scroll to that element.

Later on, see the Vue Router Section for additional configurations (container scroll, fixed header offsets, etc.).

Set CSS scroll-behavior

Somewhere in your global CSS, add the following rule to enable smooth scrolling:

css
html {
   scroll-behavior: smooth; /* or 'auto' if you prefer instant scrolling */
}

Later on, see the Scroll Behavior Section for additional scroll configurations or on how to use JS-based scrolling.

Usage

This package exports a single composable named useActiveScroll which accepts an array of targets to observe with the following signature:

typescript
type Targets = Ref | Ref

You can provide targets using template refs, HTML elements or DOM IDs.

The composable returns an object with properties to react to the active link and a method to include in your click handler: it doesn't scroll to targets and it's required if scroll is also originated by clicks.

typescript
const { setActive, activeId, activeIndex /*, ... */ } = useActiveScroll(targets)

Scenario 1 - Template refs (preferred)

If you are in charge of rendering the content nodes (e.g. using v-for), simply pass the template refs to useActiveScroll:

xml

   
   
      
{{ section.title }}

      
{{ section.content }}

   

   
   
      
         {{ link.label }}
      
   

Scenario 2 - Nuxt Content ``

Nuxt Content is great because not only automatically applies IDs to your headings, but also provides a useContent composable to query a reactive TOC in any component.

Since the object is reactive and kept in sync with the content, you can directly pass the IDs to useActiveScroll:

xml

   

   
      
         {{ link.text }}
      
   

Scenario 3 - Incoming HTML

In this case, you must query the DOM in an onMounted hook or a watcher in order to get the targets.

Many CMSs already append IDs to markup headings. In case yours doesn't, you can add them manually.

The below example also shows how to compute the sidebar links in case you are not able to retrieve them in advance in order to cover the worst case scenario.

xml

   
   

   
   
      
         {{ link.label }}
      
   

Customization

useActiveScroll options

useActiveScroll accepts an optional configuration object as last argument:

javascript
const { activeId, setActive } = useActiveScroll(targets, {
   // ...
})
Property Type Default Description
jumpToFirst boolean true Whether to set the first target on mount as active even if not (yet) intersecting.
jumpToLast boolean true Whether to set the last target as active once reached the bottom even if previous targets are entirely visible.
boundaryOffset BoundaryOffset { toTop: 0, toBottom: 0 } Boundary offset in px for each scroll direction. Tweak them to "anticipate" or "delay" target detection.
edgeOffset EdgeOffset { first: 100, last: -100 } Offset in px for fist and last target. first has no effect if jumpToFirst is true. Same for last if jumpToLast is true.
root HTMLElement | null | Ref null Scrolling element. Set it only if your content is not scrolled by the window. If null, defaults to document.documentElement.
replaceHash boolean false Whether to replace URL hash on scroll. First target is ignored if jumpToFirst is true.
overlayHeight number 0 Height in pixels of any CSS fixed content that overlaps the top of your scrolling area (e.g. fixed header). Must be paired with a CSS scroll-margin-top rule.
minWidth number 0 Whether to toggle listeners and functionalities within a specific width. Useful if hiding the sidebar using display: none.

Return object

Name Type Description
setActive (id: string | el: HTMLElement) => void :firecracker: Function to include in your click handler to ensure adaptive behavior.
isActive (id: string | el: HTMLElement) => boolean Whether the given ID or element is active or not
activeEl Ref Active target element
activeId Ref Active target ID
activeIndex Ref Index of the active target in offset order, 0 for the first target and so on.

Scroll behavior and types

You're free to choose between CSS scroll-behavior (smooth or auto), scrollIntoView or even a JS library like animated-scroll-to.

CSS (recommended)

  • Content scrolled by the window:
css
html {
   scroll-behavior: smooth; /* or 'auto' */
}
  • Content scrolled by a container:
css
.scrolling-container {
   scroll-behavior: smooth;
}

JS-based scroll

xml

   
      {{ link.label }}
   

Vue Router - Additional Configurations

Scrolling to anchors inside a container

To scroll to a target inside of a container, use scrollIntoView method and pass the target's ID.

javascript
const router = createRouter({
   // ...
   scrollBehavior(to) {
      if (to.hash) {
         // Content scrolled by a container
         if (to.name === 'PageNameUsingContainer') {
            return document.querySelector(to.hash).scrollIntoView()
         }

         // Content scrolled by the window
         return {
            el: to.hash,
            // top: 100 // Eventual fixed header (overlayHeight)
         }
      }
   },
})

:bulb: There's no need to define smooth or auto here. Adding the CSS rule is enough.

:bulb: There's no need need to set overlayHeight if using scrollIntoView as the method is aware of target's scroll-margin-top property.

Scrolling from anchors back to the page root

To navigate back to the top of the same page (e.g. clicking on browser's back button from hash to the page root), use the scroll method for containers and return top for content scrolled by the window.

javascript
const router = createRouter({
   // ...
   scrollBehavior(to, from) {
      if (from.hash && !to.hash) {
         // Content scrolled by a container
         if (
            to.name === 'PageNameUsingContainer' &&
            from.name === 'PageNameUsingContainer'
         ) {
            return document.getElementById('scrolling_container').scroll(0, 0)

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptactive-linkactive-scrollscrollvue

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类前端框架
定价开源

> 相关工具

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架