Skip to content

Affix 固钉

将页面元素固定在特定可视区域。

何时使用

当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。

基础用法

固钉默认固定在页面顶部。当页面向下滚动,元素距离顶部达到 offset 值时触发固定。

固定在底部

设置 position="bottom",元素将固定在页面底部。

指定容器

通过 target 属性指定容器(CSS 选择器),Affix 仅在容器范围内固定。当滚动超出容器时,固钉会随容器滚出视口。

监听事件

Affix 提供 changescroll 事件,可以监听固定状态的变化。

vue
<template>
  <c-affix :offset="100" @change="handleChange" @scroll="handleScroll">
    <c-button type="primary">监听事件</c-button>
  </c-affix>
</template>

<script setup>
const handleChange = (fixed) => {
  console.log("固定状态:", fixed);
};

const handleScroll = ({ scrollTop, fixed }) => {
  console.log("滚动位置:", scrollTop, "是否固定:", fixed);
};
</script>

API

Affix 属性

属性名说明类型可选值默认值
offset偏移距离(px)number0
position固定的位置stringtop / bottomtop
z-index固定时的 z-indexnumber100
target指定容器(CSS 选择器)string''

Affix 事件

事件名说明回调参数
change固定状态改变时触发(fixed: boolean)
scroll滚动时触发({ scrollTop: number, fixed: boolean })

Affix 方法

通过 ref 获取组件实例后可调用以下方法:

方法名说明参数
update手动更新固定状态
updateRoot更新占位元素尺寸

Affix 暴露属性

属性名说明类型
fixed当前是否处于固定状态Ref<boolean>