Appearance
Affix 固钉
将页面元素固定在特定可视区域。
何时使用
当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。
基础用法
固钉默认固定在页面顶部。当页面向下滚动,元素距离顶部达到 offset 值时触发固定。
固定在底部
设置 position="bottom",元素将固定在页面底部。
指定容器
通过 target 属性指定容器(CSS 选择器),Affix 仅在容器范围内固定。当滚动超出容器时,固钉会随容器滚出视口。
监听事件
Affix 提供 change 和 scroll 事件,可以监听固定状态的变化。
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) | number | — | 0 |
| position | 固定的位置 | string | top / bottom | top |
| z-index | 固定时的 z-index | number | — | 100 |
| target | 指定容器(CSS 选择器) | string | — | '' |
Affix 事件
| 事件名 | 说明 | 回调参数 |
|---|---|---|
| change | 固定状态改变时触发 | (fixed: boolean) |
| scroll | 滚动时触发 | ({ scrollTop: number, fixed: boolean }) |
Affix 方法
通过 ref 获取组件实例后可调用以下方法:
| 方法名 | 说明 | 参数 |
|---|---|---|
| update | 手动更新固定状态 | — |
| updateRoot | 更新占位元素尺寸 | — |
Affix 暴露属性
| 属性名 | 说明 | 类型 |
|---|---|---|
| fixed | 当前是否处于固定状态 | Ref<boolean> |