vue模拟微信聊天界面,输入任何文字统一回复‘你好“ 的完整代码
时间: 2024-04-02 10:35:01 浏览: 157
仿微信聊天界面
5星 · 资源好评率100%
以下是一个简单的 Vue.js 实现模拟微信聊天界面,输入任何文字统一回复‘你好’的完整代码:
```
<template>
<div class="chat-room">
<div class="chat-container">
<div class="chat-msg" v-for="(msg, index) in messages" :key="index">
<div class="chat-avatar">
<img :src="msg.avatar" alt="avatar" />
</div>
<div class="chat-content">
<div class="chat-info">
<span class="chat-name">{{ msg.name }}</span>
<span class="chat-time">{{ msg.time }}</span>
</div>
<div class="chat-text">{{ msg.text }}</div>
</div>
</div>
</div>
<div class="chat-input">
<input type="text" v-model="inputText" @keyup.enter="sendMessage" />
<button @click="sendMessage">发送</button>
</div>
</div>
</template>
<script>
export default {
name: "ChatRoom",
data() {
return {
inputText: "",
messages: [
{
avatar: "https://i.pravatar.cc/50?img=1",
name: "小明",
time: "2021-10-01 12:00",
text: "你在干嘛?",
},
{
avatar: "https://i.pravatar.cc/50?img=2",
name: "小红",
time: "2021-10-01 12:05",
text: "我在看电影,你呢?",
},
{
avatar: "https://i.pravatar.cc/50?img=3",
name: "小明",
time: "2021-10-01 12:10",
text: "我在写代码",
},
],
};
},
methods: {
sendMessage() {
if (this.inputText.trim() === "") return;
const time = new Date().toLocaleString();
const newMessage = {
avatar: "https://i.pravatar.cc/50?img=4",
name: "我",
time,
text: this.inputText,
};
this.messages.push(newMessage);
this.inputText = "";
setTimeout(() => {
const reply = {
avatar: "https://i.pravatar.cc/50?img=5",
name: "小机器人",
time: new Date().toLocaleString(),
text: "你好",
};
this.messages.push(reply);
}, 1000);
},
},
};
</script>
<style>
.chat-room {
height: 100vh;
display: flex;
flex-direction: column;
}
.chat-container {
height: calc(100% - 50px);
overflow-y: scroll;
padding: 10px;
}
.chat-msg {
display: flex;
margin-bottom: 10px;
}
.chat-avatar {
margin-right: 10px;
}
.chat-avatar img {
width: 50px;
height: 50px;
border-radius: 50%;
}
.chat-info {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
}
.chat-name {
font-weight: bold;
}
.chat-time {
color: #999;
}
.chat-text {
word-wrap: break-word;
}
.chat-input {
display: flex;
justify-content: space-between;
align-items: center;
height: 50px;
background-color: #fafafa;
padding: 10px;
}
.chat-input input {
flex: 1;
height: 30px;
border: none;
border-radius: 5px;
padding: 5px;
}
.chat-input button {
height: 30px;
margin-left: 10px;
}
</style>
```
这段代码实现了一个简单的聊天室界面,包括消息列表、发送消息输入框和发送按钮。其中,消息列表使用 `v-for` 指令遍历 `messages` 数组,每个消息包括头像、昵称、时间和文本内容。发送消息时,通过 `v-model` 指令绑定输入框的值,通过 `@keyup.enter` 监听回车键事件或者点击发送按钮时调用 `sendMessage` 方法,将新消息添加到 `messages` 数组中,并且通过 `setTimeout` 函数模拟了一个简单的自动回复,即在 1 秒后添加一个 “你好” 的消息到 `messages` 数组中。
阅读全文