vue中模拟微信聊天界面的所有代码
时间: 2023-11-18 11:02:16 浏览: 44
以下是一个简单的 Vue 组件,用于模拟微信聊天界面:
```html
<template>
<div class="chat">
<div v-for="(message, index) in messages" :key="index" class="message" :class="{ 'from-me': message.from === 'me', 'from-other': message.from === 'other' }">
<div class="avatar" v-if="message.showAvatar">{{ message.from }}</div>
<div class="bubble">{{ message.content }}</div>
</div>
<div class="input-area">
<textarea v-model="inputText" @keyup.enter="sendMessage" placeholder="Type a message"></textarea>
<button @click="sendMessage">Send</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
messages: [
{ from: 'me', content: 'Hello!', showAvatar: true },
{ from: 'other', content: 'Hi there!', showAvatar: true },
],
inputText: '',
};
},
methods: {
sendMessage() {
if (!this.inputText) {
return;
}
this.messages.push({ from: 'me', content: this.inputText, showAvatar: false });
this.inputText = '';
},
},
};
</script>
<style>
.chat {
display: flex;
flex-direction: column;
height: 100%;
}
.message {
display: flex;
align-items: flex-end;
margin: 10px;
}
.from-me .avatar {
display: none;
}
.from-other .avatar {
width: 40px;
height: 40px;
margin-right: 10px;
border-radius: 50%;
background-color: #ccc;
display: flex;
justify-content: center;
align-items: center;
}
.bubble {
max-width: 70%;
border-radius: 20px;
padding: 10px;
background-color: #eee;
}
.input-area {
display: flex;
align-items: center;
padding: 10px;
}
textarea {
flex: 1;
height: 30px;
resize: none;
margin-right: 10px;
}
button {
padding: 10px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
```
这个组件包含一个消息列表和一个输入框,通过 `v-for` 指令来渲染消息列表。每个消息都有一个 `from` 属性,表示是谁发送的,以及一个 `content` 属性,表示消息内容。输入框通过 `v-model` 指令和 `inputText` 数据属性进行双向绑定。
在发送消息时,我们通过 `sendMessage` 方法将消息添加到 `messages` 数组中,并将输入框清空。同时,我们可以根据消息发送者的不同,来决定是否显示头像。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)