uniapp聊天界面滚动到底部

发布于:2024-08-25 ⋅ 阅读:(153) ⋅ 点赞:(0)

uniapp中scroll-view聊天界面滚动到底部展示最新消息

自我记录

技术实现方案: 通过scroll-into-view 指定ID滚动到指定区域并添加scroll-with-animation动画
目前我一共两种方式:
方案1:在scroll-view 底部放置一个空标签 每次发送消息||接收消息就滚动到底部
方案2:前提条件(我这边与后端交互是我发送完消息他那边处理之后统一给我本人消息+客服消息)
所以因为交互时间问题,我这边会生成一个临时对话消息push到数组最后一项,接收到消息在pop并push新数据
最终就是我在生成临时数据时写好一个id 就实现了 滚动到指定id(好处是不用在页面底部放置空标签)坏处是频繁操作数组,由于业务场景问题没办法!

方案一

<scroll-view
  scroll-y
  class="scroll-view-main"
  @scroll="onScroll"
  scroll-with-animation
  :scroll-into-view="scrollId"
>
<!-- xxxxx 消息内容 -->
<!-- xxxxx 消息内容 -->
<!-- xxxxx 消息内容 -->
<!-- xxxxx 消息内容 -->

  <!-- 显示最新消息 -->
  <view id="msg-001"/>
</scroll-view>

发送消息后调用+接收消息时调用
注意在接收数据赋值之后 记得要有 await nextTick() 为了确保dom更新之后在滚动

// 滚动指定元素ID
const scrollId = ref<string>()

// 处理滚动位置事件
const handleScrollLocation = async (id: number | undefined) => {
  scrollId.value = id ? `msg-${id}` : undefined
  await nextTick()
  scrollId.value = undefined
}

// 发送消息公共方法
const handleSendCommon = (val: string) => {
  infoParams.value.question = val
  // 创建临时数组
  const TEMP_ITEM: ChatWriteMsgItem = {
    messageId: 999,
    role: 'user',
    message: val,
    createTime: moment().format('YYYY-MM-DD hh:mm:ss'),
  }
  handleScrollLocation(TEMP_ITEM.messageId)
  handleChatWrite()
}

如有转载 请备注原文地址!


网站公告

今日签到

点亮在社区的每一天
去签到