Skip to content
API 风格:

Anchor 锚点 ​

页面内锚点导航 + 滚动联动高亮。<nav> 语义 + aria-current="location"。

基础用法 ​

vue
<script setup>
const anchorItems = [
  { id: 'sec-1', title: '第一节' },
  { id: 'sec-2', title: '第二节', children: [{ id: 'sec-2-1', title: '第二节之一' }] },
]
</script>

<template>
  <LhAnchor :items="anchorItems" />
</template>
vue
<script>
export default {
  data() {
    return {
      anchorItems: [
        { id: 'sec-1', title: '第一节' },
        { id: 'sec-2', title: '第二节', children: [{ id: 'sec-2-1', title: '第二节之一' }] },
      ],
    }
  },
}
</script>

<template>
  <LhAnchor :items="anchorItems" />
</template>

横向排列与滚动选项 ​

direction="horizontal" 切换横向排列;smooth 关闭平滑滚动;offset 补偿锚点区域相对滚动容器顶部的偏移;target 监听指定滚动容器(默认 window)。

vue
<script setup>
const anchorItems = [
  { id: 'sec-1', title: '第一节' },
  { id: 'sec-2', title: '第二节' },
]
</script>

<template>
  <!-- 横向锚点 -->
  <LhAnchor
    :items="anchorItems"
    direction="horizontal"
    :offset="8"
    :smooth="true"
  />
</template>
vue
<script>
export default {
  data() {
    return {
      anchorItems: [
        { id: 'sec-1', title: '第一节' },
        { id: 'sec-2', title: '第二节' },
      ],
    }
  },
}
</script>

<template>
  <!-- 横向锚点 -->
  <LhAnchor
    :items="anchorItems"
    direction="horizontal"
    :offset="8"
    :smooth="true"
  />
</template>

API ​

LhAnchor Props ​

属性名说明类型默认值
items锚点数据(支持子级)[LhAnchorItem](#type-LhAnchorItem)[]—
target滚动容器(选择器或元素,默认 window)string | HTMLElement—
offset锚点区域相对滚动容器顶部的偏移(用于联动判定)number0
direction排列方向"vertical" | "horizontal"'vertical'
smooth平滑滚动booleantrue
sxsx 快速布局属性LhSxProps—

Events ​

事件名说明回调参数
change当前激活锚点变化时触发(滚动联动或点击锚点)(id: string)
click点击锚点链接时触发(先于滚动跳转抛出)(event: MouseEvent, id: string)

LhAnchorItem ​

字段说明类型
id目标元素 idstring
title显示文本string
children子级锚点LhAnchorItem[]

无障碍 ​

  • 容器为语义 <nav> 且带 aria-label;当前锚点标记 aria-current="location"
  • 链接为真实 <a href="#id">(无 JS 也能跳转,点击时增强为平滑滚动)
  • 平滑滚动在 prefers-reduced-motion: reduce 下自动降级为即时跳转

类型定义 ​

本组件对外导出的 TypeScript 类型结构如下(自动提取自 packages/components/anchor/src/types.ts 与 @lh-ui/share/core/* 源码,点击各条目展开查看完整定义;属性说明见上方 Props 表):

LhAnchorProps
ts
export interface LhAnchorProps {
  /** 锚点数据(支持子级) */
  items: LhAnchorItem[]
  /** 滚动容器(选择器或元素,默认 window) */
  target?: string | HTMLElement
  /** 锚点区域相对滚动容器顶部的偏移(用于联动判定) */
  offset?: number
  /** 排列方向 */
  direction?: 'vertical' | 'horizontal'
  /** 平滑滚动 */
  smooth?: boolean
  /** sx 快速布局属性 */
  sx?: LhSxProps
}
LhFlatAnchorItem (来自 @lh-ui/share/core/anchor)
ts
/** 扁平化后的锚点项(渲染用) */
export interface LhFlatAnchorItem {
  id: string
  title: string
  level: number
}
LhAnchorItem (来自 @lh-ui/share/core/anchor)
ts
/** 锚点项 */
export interface LhAnchorItem {
  /** 目标元素 id */
  id: string
  /** 显示文本 */
  title: string
  /** 子级锚点 */
  children?: LhAnchorItem[]
}