聊天室砍掉真实长连接,只用本地数组加 uni.setStorageSync 就搭出一个可用的 IM 骨架:左右气泡、文字与图片两种消息、进页恢复历史、发消息自动滚到底。
三招最值得抄:flex-direction: row-reverse 区分左右、border 三角画气泡尖角、nextTick + uni.pageScrollTo 滚到底。
背景
页面是分包里的聊天页,模拟「客服 / 私信」形态。没有网络层:消息就是页面里的一个数组,发出去的同时 JSON.stringify 落一份缓存,下次进来再读回来。
这种「假 IM」的价值在于界面本身——气泡方向、气泡尖角、底部输入栏、自动滚底,这四件事是所有聊天界面都绕不过去的,先把界面做对,后面换成 WebSocket 只是替换数据来源。
实现
数据结构与初值
每条消息用 isMe 区分方向、type 区分类型(txt / img)、content 存内容:
1 2 3 4 5
| import { ref, nextTick } from 'vue' import { onShow } from '@dcloudio/uni-app'
const chatlist = ref([]) const myInput = ref('')
|
左右气泡渲染
对方消息和我方消息结构几乎一样,只有外层 class 不同;type === 'txt' 渲染文字,否则渲染图片:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <view class="chat-message-orther" v-if="!item.isMe"> <image class="chat-message-avater" src="/static/bg-1.jpg" mode="aspectFit" /> <view class="chat-massage-name"> <text>lily</text> <view v-if="item.type === 'txt'" class="chat-message-text">{{ item.content }}</view> <image v-else class="chat-message-image" :src="item.content" mode="widthFix" /> </view> </view>
<view class="chat-message-my" v-else> <image class="chat-message-avater" src="/static/bg-1.jpg" mode="aspectFit" /> <view class="chat-massage-name"> <text>我</text> <view v-if="item.type === 'txt'" class="chat-message-text">{{ item.content }}</view> <image v-else class="chat-message-image" :src="item.content" mode="widthFix" /> </view> </view> </template>
|
发送文字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const scrollToBottom = () => { nextTick(() => { uni.pageScrollTo({ scrollTop: 999999, duration: 0 }) }) }
const sendMsg = () => { const content = myInput.value.trim() if (!content) return chatlist.value.push({ isMe: true, type: 'txt', content }) chatlist.value.push({ isMe: false, type: 'txt', content }) myInput.value = '' scrollToBottom() uni.setStorageSync('chatlist', JSON.stringify(chatlist.value)) }
|
原稿没有清空输入框,发第二条时会接着上一条的内容继续发;也没有 trim,一个空格也算有效消息。
发送图片
用 uni.chooseImage 从相册或相机选图,拿到临时路径后同样 push 两条:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const chooseImgAndSend = () => { uni.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: (res) => { const content = res.tempFilePaths[0] chatlist.value.push({ isMe: true, type: 'img', content }) chatlist.value.push({ isMe: false, type: 'img', content }) scrollToBottom() uni.setStorageSync('chatlist', JSON.stringify(chatlist.value)) } }) }
|
res.tempFilePaths 是数组(count 可大于 1),取第 0 项之前要先确认它非空;fail 分支原稿完全没处理,用户取消选图时不会有任何反馈。
进页恢复历史
1 2 3 4 5 6 7 8 9 10 11
| onShow(() => { const cache = uni.getStorageSync('chatlist') if (!cache) return try { chatlist.value = JSON.parse(cache) } catch (e) { uni.removeStorageSync('chatlist') return } scrollToBottom() })
|
写在 onShow 而不是 onLoad,是为了「从其它页面返回时也能刷新一次」;但要注意:如果缓存里的图片是临时路径,重启小程序后这些消息会全部变裂图。
样式:左右分栏与气泡尖角
row-reverse 实现我方靠右——父容器反向排列,内层 align-items: flex-end 让内容靠右,不用重写一套 DOM:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| .chat-message-orther, .chat-message-my { display: flex; width: 100%; align-items: center; } .chat-message-my { flex-direction: row-reverse; .chat-massage-name { display: flex; flex-direction: column; align-items: flex-end; } }
|
伪元素画气泡尖角——透明边框 + 只给一条边上色,得到一个指向头像的三角形:
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
| .chat-message-text { position: relative; padding: 6px 10px; background-color: #fff; border-radius: 8px; &::before { content: ''; position: absolute; top: 50%; left: -16px; margin-top: -8px; width: 0; height: 0; border: 8px solid transparent; border-right: 8px solid #fff; } }
.chat-message-my .chat-message-text { background-color: seagreen; &::before { left: auto; right: -16px; border-right: 8px solid transparent; border-left: 8px solid seagreen; } }
|
底部固定输入栏
position: fixed; bottom: 0 把输入框、图片按钮、发送按钮钉在底部;消息列表用 padding-bottom 给它让位:
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
| .chat-list { padding-bottom: 80px; }
.footer { position: fixed; left: 0; bottom: 0; width: 100%; display: flex; align-items: center; padding: 5px 0 20px; background-color: #ccc; border-top: 1px solid gray; .consult { flex: auto; padding: 5px 10px; border-radius: 6px; background-color: #fff; } .send { flex: none; padding: 4px 8px; color: #fff; background-color: green; border-radius: 6px; } }
|
padding-bottom: 80px 要跟着输入栏的实际高度走(含 padding 与安全区);iPhone 全面屏还要再加 constant(safe-area-inset-bottom) / env(safe-area-inset-bottom),否则输入栏会压在小白条上。
踩坑
width/height: 100vw / 100vh 配 row-reverse 会让元素消失:原稿文件头部的注释就记着这个坑,解法是把容器宽高改成 100%。遇到「元素莫名不见」,先怀疑宽高单位。
- **动态图片路径不能带
@**:@ 只在静态 src 里被编译期解析,一旦路径来自数据就必须写 /static/...。
scrollTop: 999999 是土办法:超大值兜底简单,但内容比这个数还高就不够了。更稳的是用 scroll-view 的 scroll-into-view 滚到最后一条消息的 id,或者用 uni.createSelectorQuery 量出内容高度再滚。
duration: 0 是为了瞬移:进页恢复历史时不需要滚动动画;发新消息时可以给 200ms,让它平滑滚下去,观感更好。
nextTick 不能省:push 之后 DOM 还没渲染完,立刻滚底会停在上一条消息的位置。
- 缓存里的图片会失效:
chooseImage 给的是临时路径,重启小程序后变裂图。真实 IM 必须先把图上传,再把永久 URL 存进消息体。
JSON.parse 要兜住:缓存可能被别处写坏,解析失败会直接抛错挡住整个 onShow,页面看起来像白屏。
小结
聊天的界面对成本比很高:不碰网络,一个数组加一份缓存就把 IM 的观感做出来了。
可迁移的就是三样:row-reverse 做左右分栏、border 三角做气泡尖角、nextTick + pageScrollTo 做自动滚底。这三招几乎出现在每一个聊天或评论界面里,改的只是数据和配色。