微信小程序云开发实现聊天(聊天室,一对一聊天)

主要使用小程序云开发的watch 监听集合中符合查询条件的数据的更新事件,支持 where, orderBy, limit,不支持 field。

一、云开发数据表设计

一个是用户表user :用户头像(avatarUrl)、昵称(nickName)等用户基本信息,可在授权登录时获取并保存到user表中。

一个是对话表存储message:发送者(from)、接受者(to)、消息(message数组)

消息利用云开发的push 之前添加到message数组中。

信息收发使用watch 根据from to查询监听消息改变

二、页面代码

chat.js

const app = getApp()
const { db, user } = app
const User = db.collection('user')
const Message = db.collection('message')
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    InputBottom: 0,
    user,
    to: '', // 发送给谁
    toInfo: {}, //接受者信息
    queueWatch: '',// 消息监听
    content: '', // 发送内容
    message: [], // 聊天信息
    scrollLast: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({ to }) {
    this.setData({ to })
    this.getToInfo()
  },

  /**
   * 获取接受者信息
   */
  getToInfo() {
    const { to } = this.data
    const that = this
    User.doc(to).get({
      success: ({ data }) => {
        that.setData({ toInfo: data })
        wx.setNavigationBarTitle({
          title: '好友:' + data.nickName,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { to, user } = this.data
    this.handleCreate(to, user._id)
    this.handleWatch(true)
  },
  //消息自动到底部
  getScollBottom() {
    this.setData({ scrollLast: 'lastPosition' })
  },
  //创建聊天
  handleCreate(to, from, cb) {
    Message.where({ to, from }).get({
      success: ({ data }) => {
        if (data.length == 0) {
          Message.add({
            data: { to, from, message: [] },
            success: () => {
              (typeof cb == 'function') && cb()
            }
          })
        } else (typeof cb == 'function') && cb()
      }
    })
  },
  //添加信息
  handleAddMessage(to, from, message, cb) {
    Message.where({ to, from }).update({
      data: { message: _.push(message) },
      success: ({ data }) => {
        (typeof cb == 'function') && cb()
      }
    })
  },
  // 信息发送
  handleSend() {
    const { to, user, content } = this.data
    if (!content) return
    const from = user._id
    const message = { from, content }
    const that = this
    this.handleAddMessage(to, from, message, () => {
      console.log('添加成功')
      //接受者创建对话和添加信息
      that.handleCreate(from, to, () => {
        that.handleAddMessage(from, to, message, () => {
          that.setData({ content: '' })
        })
      })
    })
  },
  /**
   * 监听值改变
   */
  handleInput(e) {
    const { name, value } = app.dataset(e)
    const obj = {}
    obj[name] = value
    this.setData(obj)
  },
  InputFocus({ detail: { height } }) {
    this.setData({ InputBottom: height })
  },
  InputBlur(e) {
    this.setData({ InputBottom: 0 })
  },

  /**
   * 监听消息变化
   */
  handleWatch: async function (watch) {
    let { queueWatch, to, user } = this.data
    const that = this
    if (watch && !queueWatch) { // 监听
      queueWatch = Message.where({ to, from: user._id })
        .watch({// 发起监听
          onChange: function ({ docs }) {
            const { message = [] } = docs[0] || {}
            that.setData({ message })
            that.getScollBottom()
          },
          onError: function (err) {
            console.error('the watch closed because of error', err)
          }
        })
      this.setData({ queueWatch })
    } else if (!watch && queueWatch) { // 取消监听
      await queueWatch.close()
      this.setData({ queueWatch: '' })
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onHide: function () {
    this.handleWatch(false) // 取消监听
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

chat.wxml

<scroll-view style="max-height: 100vh" scroll-y="true" scroll-into-view="{{scrollLast}}">
	<view  class="cu-chat">
		<block wx:for="{{message}}" wx:key="index">
			<!-- 自已发送的 -->
			<view wx:if="{{user._id==item.from}}" class="cu-item self">
				<view class="main">
					<view class="content bg-green shadow">
						<text>{{item.content}}</text>
					</view>
				</view>
				<image class="cu-avatar radius" src="{{user.avatarUrl}}"></image>
				<view wx:if="{{false}}" class="date">2018年3月23日 13:23</view>
			</view>
			<!-- 别人发送的 -->
			<view wx:else class="cu-item">
				<image class="cu-avatar radius" src="{{toInfo.avatarUrl}}"></image>
				<view class="main">
					<view class="content shadow">
						<text>{{item.content}}</text>
					</view>
				</view>
				<view wx:if="{{false}}" class="date "> 13:23</view>
			</view>
		</block>
	</view>
	<view id="lastPosition" style="height: 45px;"></view>
</scroll-view>
<view class="cu-bar foot input" style="bottom:{{InputBottom}}+px">
	<view class="action">
		<text class="cuIcon-comment text-grey"></text>
	</view>
	<input class="solid-bottom" value="{{content}}" data-name="content" adjust-position="false" focus="false" maxlength="300" cursor-spacing="10" bindfocus="InputFocus" bindblur="InputBlur" bindinput="handleInput"></input>
	<view wx:if="{{false}}" class="action">
		<text class="cuIcon-emojifill text-grey"></text>
	</view>
	<button class="cu-btn bg-green shadow" bindtap="handleSend">发送</button>
</view>

页面样式使用的是colorui css 

三、效果

 

 

 

  • 11
    点赞
  • 78
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
微信小程序客服页面设计是指在微信小程序中为用户提供在线客服服务的页面设计。以下是一些常见的微信小程序客服页面设计要点: 1. 页面布局:客服页面应该简洁明了,突出主要功能区域,例如聊天窗口、输入框和发送按钮等。可以采用分屏布局,将聊天记录和输入框分别放置在上下两个区域。 2. 聊天界面:聊天界面应该清晰易懂,显示用户与客服的对话记录。可以使用气泡式的消息框,将用户和客服的消息分别显示在左右两侧,以区分身份。 3. 输入框:输入框应该方便用户输入文字,并提供发送按钮。可以考虑在输入框上方添加常用功能按钮,如发送图片、表情等。 4. 多媒体支持:客服页面应该支持发送多种类型的消息,如文字、图片、语音等。用户可以通过点击按钮或者拖拽文件到输入框来发送多媒体消息。 5. 消息提示:客服页面应该及时提示用户新消息的到来,可以通过声音、震动或者红点等方式提醒用户。 6. 客服信息展示:在客服页面中展示客服的基本信息,如头像、昵称、在线状态等。这样可以增加用户对客服的信任感。 7. 历史记录:为了方便用户查看之前的对话记录,可以提供历史记录功能。用户可以滚动查看之前的聊天记录,并且可以通过搜索功能快速找到需要的信息。 8. 客服评价:为了改进客服服务质量,可以在客服页面中添加客服评价功能。用户可以对客服的服务进行评分和留言,以便后续改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少十步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值