Vue 聊天列表滚动方案

目前只实现了自动滚动到底部。还未实现下拉加载更多。如果需要在滚动触顶时加载更多,同时保持滚动位置,可能需要更加复杂的方案。

  1. 初始化时自动滚动到底部。
  2. 当列表内容变化时,如果用户当前位置接近底部且未向上滚动,则自动滚动到底部。
  3. 如果用户正在浏览上方内容,则保持当前滚动位置。
typescript 复制代码
import { useResizeObserver, useScroll, whenever } from "@vueuse/core";

export type MaybeHTMLElement = MaybeRefOrGetter<HTMLElement | null | undefined>;
/**
 * 聊天滚动组合函数
 * @param options - 配置选项
 * @param options.scrollTarget - 滚动容器元素
 * @param options.listElement - 列表内容元素,用于监听尺寸变化
 * @returns 包含滚动到底部方法的对象
 * @remarks
 * 该函数提供智能滚动行为:
 * 1. 初始化时自动滚动到底部
 * 2. 当列表内容变化时,如果用户当前位置接近底部且未向上滚动,则自动滚动到底部
 * 3. 如果用户正在浏览上方内容,则保持当前滚动位置
 */
export const useChatScroll = (options: {
  scrollTarget: MaybeHTMLElement;
  listElement: MaybeHTMLElement;
}) => {
  const scrollTarget = computed(() => toValue(options.scrollTarget));
  const { directions } = useScroll(scrollTarget);
  /**
   * 滚动到底部
   * @param options - 滚动选项
   * @param options.behavior - 滚动行为,"auto" 为瞬间滚动,"smooth" 为平滑滚动
   */
  const scrollToBottom = (options?: { behavior?: "auto" | "smooth" }) => {
    if (!scrollTarget.value) return;
    scrollTarget.value.scrollTo({
      top: scrollTarget.value.scrollHeight,
      behavior: options?.behavior,
    });
  };

  /**
   * 当滚动容器元素被挂载后,自动滚动到底部
   */
  whenever(scrollTarget, () => {
    const timer = setInterval(scrollToBottom, 60);
    // 持续滚动 1 秒
    setTimeout(() => clearInterval(timer), 1000);
  });

  /**
   * 当滚动条距离底部的距离小于该值时,会自动滚动到底部
   */
  const BOTTOM_THRESHOLD = 100;

  const listElement = computed(() => toValue(options.listElement));
  useResizeObserver(listElement, () => {
    if (!scrollTarget.value) return;
    const { scrollHeight, scrollTop, clientHeight } = scrollTarget.value;
    const scrollBottom = scrollHeight - scrollTop - clientHeight;
    // 如果正在浏览上方内容,则跳过
    if (scrollBottom > BOTTOM_THRESHOLD) return;
    // 如果正在向上方滚动,则跳过
    if (directions.top) return;
    // 正常情况,自动滚动到底部
    scrollToBottom({ behavior: "smooth" });
  });

  return { scrollToBottom };
};
相关推荐
AI开源软件1 小时前
SpringBoot多系统同步:别让“同名数据”变成“同一条数据”
vue.js·spring boot·企业管理·mdm
code2cat1 小时前
Vue与React Native任务验收:断网改了标题,重新联网后该看到什么?
vue.js·react native·react.js
FYKJ_20102 小时前
springboot网上汽车租赁系统93523-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·汽车·课程设计
AI开源软件14 小时前
用MQTT跑通一台模拟设备:看懂IoT产品、物模型和告警
java·vue.js·spring boot·物联网·mqtt·iot·企业管理
RuoyiOffice1 天前
Vue3商城后台实战:一款商品,从规格上架走到部分退款
vue.js·spring boot·vue3·商城系统·商城·企业管理·ruoyi office
htzyl2062 天前
Vue3中watch的deep默认值:reactive与ref为什么相反
前端·vue.js
qq_274475152 天前
第 21 篇:Proxy 代理与 Reflect:数据劫持基础,Vue 响应式底层原理前置
前端·javascript·vue.js
北城笑笑2 天前
Vue 115 ,上篇:给智能体装上计费表,行知订阅次数额度与每日额度双规则设计( 需求分析与方案设计,Vue3 + RuoYi 3.9.2 + 主子账号 )
java·前端·javascript·数据库·vue.js·后端·vue
anyup2 天前
2027 年初,uni-app 官方停更,老项目该何去何从?
前端·vue.js·uni-app
徐小夕2 天前
JitKnow 5.0发布:让AI知识库变成可组装的知识中台
前端·vue.js·github