帮我用vue写一个聊天页
时间: 2023-03-21 16:00:14 浏览: 36
好的,下面是一个简单的聊天页的Vue代码示例:
```html
<template>
<div class="chat">
<div class="chat-header">
<h1>Chat Room</h1>
</div>
<div class="chat-messages">
<div v-for="message in messages" :key="message.id">
<p>{{ message.text }}</p>
<small>{{ message.timestamp }}</small>
</div>
</div>
<div class="chat-input">
<form @submit.prevent="sendMessage">
<input v-model="newMessage" type="text" placeholder="Type your message here" />
<button type="submit">Send</button>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
messages: [
{
id: 1,
text: "Hello!",
timestamp: new Date()
},
{
id: 2,
text: "How are you?",
timestamp: new Date()
}
],
newMessage: ""
};
},
methods: {
sendMessage() {
if (this.newMessage !== "") {
this.messages.push({
id: this.messages.length + 1,
text: this.newMessage,
timestamp: new Date()
});
this.newMessage = "";
}
}
}
};
</script>
<style>
.chat {
display: flex;
flex-direction: column;
height: 100%;
}
.chat-header {
background-color: #333;
color: #fff;
padding: 20px;
}
.chat-messages {
flex: 1;
overflow-y: scroll;
padding: 20px;
}
.chat-messages p {
background-color: #f1f0f0;
padding: 10px;
border-radius: 10px;
margin-bottom: 10px;
}
.chat-messages small {
display: block;
text-align: right;
margin-top: 5px;
color: #aaa;
}
.chat-input {
background-color: #eee;
padding: 20px;
}
.chat-input input {
padding: 10px;
width: 80%;
border-radius: 5px;
border: none;
margin-right: 10px;
}
.chat-input button {
background-color: #4caf50;
color: #fff;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
</style>
```
这段代码会渲染出一个简单的聊天页面,其中包含一个标题、一组聊天消息和一个输入框和发送按钮。用户可以在输入框中输入消息并点击发送按钮将消息发送到聊天框中。
请注意,这只是一个简单的示例,您可以根据自己的需求进行修改和扩展。