0
点赞
收藏
分享

微信扫一扫

微信小程序聊天界面进入自动滚动到底部,翻看历史聊天记录,收到的新消息不会马上置底,如收到新消息出现 底部有更多消息字样

南陵王梁枫 2022-03-12 阅读 103

重点看标红部分,其他代码只是写的上下逻辑,可忽略

wxml:

<view style="position: relative;width: 100%;height: 100%;">

        <scroll-view scroll-y="{{true}}" scroll-with-animation="{{true}}" scroll-into-view="{{scrollBottom}}" class="barrage" bindscrolltolower="scrollBottomMet">

          <view class="forBarrage" wx:for="{{chatRecord}}" wx:key="key">

            <text decode="{{true}}" style="{{item.msgType==2?'color:orange':item.msgType==3?'color:green':item.isManage==1?'color:red':item.isSelf?'':'color:yellow'}}">{{item.nickName}}{{item.msgType==1?':':'&nbsp;'}}</text>

            <text>{{item.chatContent}}</text>

          </view>

          <view id="{{scrollBottom}}"></view>

        </scroll-view>

        <view class="hasMoreChat" wx:if="{{hasMore}}" bindtap="toBottom">底部有新消息 ↓</view>

      </view>

index.js:

Page({

  /**

   * 页面的初始数据

   */

  data: {

     hasMore: false,

     scrollBottom: "1rpx",

    }

  //当收到服务器来信时

    socketTask.onMessage(res => {

      let msg = res.data,

        msgArr = msg.split(":"),

        newMsg = msg.split(msgArr[0] + ":")[1],

        content = newMsg.split("-");

      if (msg.indexOf("TextMsg:") != -1) { //文字信息=>TextMsg:用户编号-昵称-消息内容-是否管理员

        let isSelf = false,chatMsg=JSON.parse(newMsg)

        if (chatMsg.commonCode == _this.data.markCustCode) { //本人所发

          isSelf = true

        }

        let chatRecord = _this.data.chatRecord;

        chatMsg.isSelf=isSelf

        chatMsg.msgType=1 //普通消息

        chatRecord.push(chatMsg)

        _this.setData({

          chatRecord,

          // scrollTop: _this.data.swiperHeight * chatRecord.length,有新消息来自动回到底部

          //看历史消息的时候,有新消息来,底部出现 有更多消息字样

          hasMore: true

        })

//进入自动在底部  往后台发请求那数据

getChatRecord() {

    let _this = this

    POST_UNLOAD('liveChatRecord/list', {

      liveId: _this.data.info.liveId,

      round: _this.data.info.round,

      current: 1,

      size: 50,

      isAsc: false

    }, function (res, resCode) {

      if (resCode == 200) {

        let {

          result

        } = res.data

        result.records.reverse()

        result.records.forEach(e => {

          e.isSelf = (e.markCustCode == _this.data.markCustCode) ? true : false

          e.msgType = 1 //普通消息

        })

        _this.setData({

          chatRecord: result.records,

          scrollBottom: "scrollBottom"

        })

      }

    });

  },

//点击更多消息 底部有新消息字样消失

scrollBottomMet() {

    this.setData({

      hasMore: false

    })

  },

//点击底部有新消息字样立马置底

  toBottom() {

    this.setData({

      scrollBottom: "scrollBottom"

    })

  },

}) 

 

举报

相关推荐

0 条评论