1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| Page({ /** * 页面的初始数据 */ data: { scrollTop: 0, list: [] }, id: 0, /** 生命周期函数--监听页面加载*/ onLoad: function (options) { wx.connectSocket({ //本地服务器地址 url: 'ws://localhost:3000', }) //连接成功 wx.onSocketOpen((res) => { console.log('连接成功') }) wx.onSocketMessage((res) => { var data = JSON.parse(res.data) data.id = this.id++ data.role = 'server' var list = this.data.list list.push(data) this.setData({ list: list }) this.rollingBottom() }) }, //发送内容 message: '', send() { //判断发送内容是否为空 if (this.message) { wx.sendSocketMessage({ data: this.message, }) //我自己的消息 console.log(this.data.list) var list = this.data.list list.push({ id: this.id++, content: this.message, role: 'me' }) this.setData({ list: list }) this.rollingBottom() } else { //弹出提示框 wx.showToast({ title: '消息不能为空哦~', icon: 'none', duration: 2000 }) } }, //监听Input值的改变 bindChange(res) { this.message = res.detail.value }, //页面卸载,关闭连接 onUnload: function () { wx.closeSocket() console.log('连接已断开') }, //聊天内容始终显示在最低端 rollingBottom(e) { wx.createSelectorQuery().selectAll('.list').boundingClientRect(rects => { rects.forEach(rect => { this.setData({ scrollTop: rect.bottom }) }) }).exec() } })
|