我们都知道小程序是不能直接操作dom的,所以做即时通讯聊天功能的时候也就不能像之前做的一样:点击发送的时候,拼接一个节点到页面上。话不多说,以下是效果和代码:
-----------------------chat.js------------------------------
// pages/chat/chat.jsPage({ ??/** ??* 页面的初始数据 ??*/ ?data: { ???lists: [ ?????????], ???scrollTop: 100,//设置滚动条到顶部的距离 ?????centence:‘‘, ???length:0, ?}, ?//点击发送以后的事件处理函数 ???addItemFn: function () { ???var {lists} = this.data; ???var newData = { value: this.data.centence }; ???lists.push(newData); ???this.setData({ ?????lists: lists, ?????centence:‘‘ ???}) ???console.log(lists) ?}, ?inputFunc:function(e){ ???this.setData({ ?????centence: e.detail.value ???}) ???// console.log(this.data.centence) ?}, ?/** ??* 生命周期函数--监听页面加载 ??*/ ?onLoad: function (options) { ????}, ?/** ??* 生命周期函数--监听页面初次渲染完成 ??*/ ?onReady: function () { ?????}, ?/** ??* 生命周期函数--监听页面显示 ??*/ ?onShow: function () { ???}, ?/** ??* 生命周期函数--监听页面隐藏 ??*/ ?onHide: function () { ???}, ?/** ??* 生命周期函数--监听页面卸载 ??*/ ?onUnload: function () { ???}, ?/** ??* 页面相关事件处理函数--监听用户下拉动作 ??*/ ?onPullDownRefresh: function () { ???}, ?/** ??* 页面上拉触底事件的处理函数 ??*/ ?onReachBottom: function () { ???}, ?/** ??* 用户点击右上角分享 ??*/ ?onShareAppMessage: function () { ???}})
------------------------chat.wxml-------------------------------
<view class="container"> ?<!-- <button type="primary" >添加</button> --> ?<scroll-view class="scroll" scroll-y="true" scroll-top="{{scrollTop}}"> ???<block wx:for="{{lists}}" wx:key="*this"> ?????<view class="item" data-index="{{index}}" id="item{{index}}" class="myMsg flexBox"> ???????<view class="msg"><view class="eachMsg">{{item.value}}</view><text class="iconfont icon-triangle-right"></text></view> ???????<image src=‘/assets/images/chatdoc.png‘></image> ?????</view> ???</block> ?</scroll-view> ?<view class="bottom"> ???<input placeholder="" auto-focus name="centences" bindinput=‘inputFunc‘ value="{{centence}}" auto-focus/> ???<view class=‘icon‘ bindtap=‘addItemFn‘> ?????<text>发送</text> ???</view> ?</view></view>
望互相指教。。。。
小程序即时聊天(仅页面功能,未接websocket)
原文地址:https://www.cnblogs.com/crystal-wei/p/9168241.html