vue聊天界面实现
Vue聊天界面实现
数据绑定与列表渲染
使用Vue的v-for指令渲染消息列表,结合v-model实现双向数据绑定
<template>
<div class="chat-container">
<div v-for="(msg, index) in messages" :key="index" class="message">
<span class="sender">{{ msg.sender }}:</span>
<span class="content">{{ msg.content }}</span>
</div>
<input v-model="newMessage" @keyup.enter="sendMessage"/>
</div>
</template>
<script>
export default {
data() {
return {
messages: [],
newMessage: ''
}
}
}
</script>
消息发送功能
实现消息发送方法,处理用户输入并清空输入框
methods: {
sendMessage() {
if (this.newMessage.trim() === '') return
this.messages.push({
sender: 'User',
content: this.newMessage
})
this.newMessage = ''
this.scrollToBottom()
}
}
自动滚动到底部
在消息列表更新后自动滚动到最新消息位置
scrollToBottom() {
this.$nextTick(() => {
const container = this.$el.querySelector('.chat-container')
container.scrollTop = container.scrollHeight
})
}
样式设计
添加基础样式美化聊天界面
.chat-container {
height: 400px;
overflow-y: auto;
border: 1px solid #eee;
padding: 10px;
}
.message {
margin: 8px 0;
padding: 8px;
background: #f5f5f5;
border-radius: 4px;
}
.sender {
font-weight: bold;
margin-right: 5px;
}
input {
width: 100%;
padding: 8px;
margin-top: 10px;
box-sizing: border-box;
}
响应式设计优化
添加媒体查询适应不同屏幕尺寸
@media (max-width: 600px) {
.chat-container {
height: 300px;
}
}
消息时间戳
增强消息对象包含时间信息
this.messages.push({
sender: 'User',
content: this.newMessage,
timestamp: new Date().toLocaleTimeString()
})
消息气泡样式
区分发送方和接收方的消息样式
.message.user {
background: #e3f2fd;
align-self: flex-end;
}
.message.other {
background: #f1f1f1;
align-self: flex-start;
}






