写一个vue3的机器人聊天页面
时间: 2023-10-08 12:14:20 浏览: 69
好的,这是一个关于 Vue3 的机器人聊天页面的代码示例:
<template>
<div class="chat-container">
<div class="chat-header">机器人聊天</div>
<div class="chat-window">
<div class="messages" ref="messages">
<div v-for="(message, index) in messages" :key="index" :class="message.type">
<div class="message-content">{{ message.content }}</div>
</div>
</div>
<div class="input-container">
<input type="text" v-model="newMessage" @keyup.enter="sendMessage" placeholder="请输入消息...">
<button @click="sendMessage">发送</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
messages: [], // 存放聊天记录
newMessage: '' // 新消息
}
},
methods: {
// 发送消息
sendMessage() {
if (this.newMessage) {
this.messages.push({
type: 'sent',
content: this.newMessage
});
// 发送请求,获取机器人回复
// 省略异步请求代码,假设回复内容为 response
const response = '您好,我是一个机器人。';
this.messages.push({
type: 'received',
content: response
});
// 滚动到底部显示最新消息
this.$nextTick(() => {
this.$refs.messages.scrollTo(0, this.$refs.messages.scrollHeight)
})
// 清空新消息
this.newMessage = '';
}
}
}
}
</script>
<style scoped>
.chat-container {
display: flex;
flex-direction: column;
align-items: center;
padding-top: 20px;
}
.chat-header {
font-size: 24px;
font-weight: bold;
margin-bottom: 20px;
}
.chat-window {
display: flex;
flex-direction: column;
align-items: center;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
border-radius: 10px;
overflow: hidden;
}
.messages {
height: 400px;
width: 100%;
padding: 10px;
overflow-y: scroll;
}
.message-content {
padding: 8px 12px;
border-radius: 10px;
}
.sent {
align-self: flex-end;
background-color: #EDF2F7;
margin-bottom: 10px;
}
.received {
align-self: flex-start;
background-color: #F7FAFC;
margin-bottom: 10px;
}
.input-container {
display: flex;
align-items: center;
padding: 10px;
}
input {
flex: 1;
border-radius: 10px;
border: none;
padding: 8px 12px;
font-size: 16px;
margin-right: 10px;
}
button {
border: none;
border-radius: 10px;
padding: 8px 12px;
background-color: #3182CE;
color: white;
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s ease;
}
button:hover {
background-color: #2C5282;
}
</style>
希望这个示例对你有帮助!
阅读全文