uniapp实现聊天框
uniapp实现聊天框的基本步骤
页面结构设计
使用<scroll-view>组件作为聊天容器,确保消息过多时可滚动。消息列表通过v-for循环渲染,每条消息区分发送方(右侧)和接收方(左侧)样式。底部固定输入框区域,包含<input>和发送按钮。
<template>
<view class="chat-container">
<scroll-view scroll-y class="message-list">
<view v-for="(msg, index) in messages" :key="index"
:class="['message', msg.isMe ? 'right' : 'left']">
<text>{{ msg.content }}</text>
</view>
</scroll-view>
<view class="input-area">
<input v-model="inputText" placeholder="输入消息" />
<button @click="sendMessage">发送</button>
</view>
</view>
</template>
样式调整
通过CSS区分消息方向,发送方消息右对齐且背景色不同,接收方左对齐。固定输入框在底部,避免键盘弹出时遮挡。
.message-list {
height: calc(100vh - 100px);
padding: 10px;
}
.message {
margin: 5px;
padding: 8px;
border-radius: 5px;
max-width: 70%;
}
.left {
background: #f0f0f0;
align-self: flex-start;
}
.right {
background: #007aff;
color: white;
align-self: flex-end;
}
.input-area {
position: fixed;
bottom: 0;
width: 100%;
padding: 10px;
background: white;
display: flex;
}
数据与逻辑处理
在data中定义消息数组和输入框绑定变量。发送消息时将新消息加入数组,并清空输入框。可模拟接收消息通过定时器或WebSocket。
export default {
data() {
return {
messages: [
{ content: "你好!", isMe: false },
{ content: "你好,有什么可以帮您?", isMe: true }
],
inputText: ''
}
},
methods: {
sendMessage() {
if (this.inputText.trim()) {
this.messages.push({ content: this.inputText, isMe: true });
this.inputText = '';
// 模拟回复
setTimeout(() => {
this.messages.push({ content: "已收到您的消息", isMe: false });
}, 1000);
}
}
}
}
进阶功能扩展
消息时间戳显示
每条消息对象增加time字段,使用过滤器或方法格式化时间显示。
methods: {
formatTime(time) {
return new Date(time).toLocaleTimeString();
}
}
图片/文件支持
通过<uni-file-picker>组件上传文件,消息类型字段区分文本和图片,渲染时动态选择<image>或<text>。
消息持久化
使用uni.setStorageSync本地存储消息记录,或在onLoad中从服务器拉取历史消息。
onLoad() {
const history = uni.getStorageSync('chatHistory');
if (history) this.messages = history;
},
watch: {
messages: {
handler(newVal) {
uni.setStorageSync('chatHistory', newVal);
},
deep: true
}
}
注意事项
- 使用
scroll-view时需设置固定高度,否则无法滚动。 - 输入框区域建议使用
position: fixed,避免键盘弹出时布局错乱。 - 长列表渲染可考虑使用
<uni-list>优化性能。 - 真机测试时注意iOS和Android的键盘差异,可能需要调整
windowSoftInputMode。







