vue 实现 H5 移动端 即时聊天布局代码
时间: 2024-05-24 16:10:33 浏览: 104
<template>
<div class="chat-container">
<!-- 聊天消息列表 -->
<div class="message-list">
<div class="message-item" v-for="message in messages" :key="message.id">
<div class="avatar"><img :src="message.avatar" alt=""></div>
<div class="message-content">
<div class="name">{{ message.name }}</div>
<div class="text">{{ message.text }}</div>
<div class="time">{{ message.time }}</div>
</div>
</div>
</div>
<!-- 发送消息表单 -->
<div class="send-form">
<input type="text" class="input-message" v-model="newMessage" placeholder="请输入消息内容">
<button class="send-button" @click="sendMessage">发送</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
messages: [
{
id: 1,
name: '小明',
avatar: 'https://avatars.githubusercontent.com/u/6224295?v=4',
time: '2021-10-01 10:00:00',
text: '你好啊,我想问一下这个聊天布局怎么实现的?'
},
{
id: 2,
name: '小红',
avatar: 'https://avatars.githubusercontent.com/u/6224295?v=4',
time: '2021-10-01 10:05:00',
text: '这个是使用 Vue 实现的,主要是利用了 Flex 布局和 Vue 组件的特性。'
}
],
newMessage: ''
}
},
methods: {
// 发送消息
sendMessage() {
if (this.newMessage.trim() !== '') {
const message = {
id: this.messages.length + 1,
name: '小明',
avatar: 'https://avatars.githubusercontent.com/u/6224295?v=4',
time: new Date().toLocaleString(),
text: this.newMessage
}
this.messages.push(message)
this.newMessage = ''
}
}
}
}
</script>
<style scoped>
.chat-container {
display: flex;
flex-direction: column;
height: 100%;
}
.message-list {
flex: 1;
overflow-y: auto;
padding: 10px;
}
.message-item {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.avatar {
width: 40px;
height: 40px;
margin-right: 10px;
border-radius: 50%;
overflow: hidden;
}
.avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
.message-content {
flex: 1;
}
.name {
font-size: 14px;
font-weight: bold;
margin-bottom: 5px;
}
.text {
font-size: 16px;
}
.time {
font-size: 12px;
color: #666;
margin-top: 5px;
}
.send-form {
display: flex;
align-items: center;
padding: 10px;
background-color: #fff;
}
.input-message {
flex: 1;
height: 30px;
padding: 0 10px;
border: 1px solid #ccc;
border-radius: 15px;
outline: none;
}
.send-button {
margin-left: 10px;
width: 60px;
height: 30px;
border: none;
border-radius: 15px;
background-color: #42b983;
color: #fff;
cursor: pointer;
outline: none;
}
</style>
阅读全文