本文主要是介绍vue 实现简单AI聊天程序(一) elementui 聊天框编写,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这个系列的目标是开发一个AI聊天前端界面+后端问答程序,
探索前端界面开发。
尝试后端对接阿里云千问大模型,后续还会更新自己部署的大模型。
这一期用elmentui来开发一个聊天框的前端,根据用户发送的内容,AI会返回一个一模一样的内容,在纯前端模拟聊天的效果。同时界面可以自适应当前浏览器的大小,聊天记录如果超过了聊天框的界面,则可以滚动。
开发完的效果如下:
1 开发前端
新建一个Chat.vue,里面采用el-card
<template><el-card><div class="chat-box" ref="chatBox"><div v-for="(msg, index) in messages" :key="index" class="message"><div v-if="msg.type === 'user'" class="user-message"><img :src="avatar" alt="User" class="avatar" /><div class="message-content user-message-content">{{ msg.content }}</div></div><div v-if="msg.type === 'bot'" class="bot-message"><img :src="avatar_bot" alt="Bot" class="avatar" /><div class="message-content bot-message-content">{{ msg.content }}</div></div></div></div><div class="input-area"><el-inputv-model="input"placeholder="请输入您的问题..."@keyup.enter.native="sendMessage"class="input-field":style="{ maxWidth: 'calc(100% - 100px)' }"></el-input><el-button type="primary" @click="sendMessage">发送</el-button></div></el-card>
</template>
需要注意的是这段代码,通过这个可以实现按键盘的enter发送消息的功能:
@keyup.enter.native="sendMessage"
script部分
<script>
export default {data() {return {input: '',messages: [],avatar: localStorage.getItem('avatar'),avatar_bot: require('@/assets/robot.png')};},methods: {sendMessage() {console.log('消息:', this.input)if (this.input.trim() === '') return;this.messages.push({ type: 'user', content: this.input });const userInput = this.input;this.input = '';setTimeout(() => {this.messages.push({ type: 'bot', content: `您说了: ${userInput} \n` });this.scrollToBottom();}, 500);this.scrollToBottom();},scrollToBottom() {this.$nextTick(() => {this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;});}}
};
</script>
style部分:
<style scoped>
.chat-box {height: calc(100vh - 210px);overflow-y: auto;padding: 10px;border-bottom: 1px solid #dcdfe6;
}
.input-area {display: flex;align-items: center;margin-top: 10px;
}
.message {margin: 10px 0;display: flex;align-items: center;
}
.user-message, .bot-message {margin-top: 2px;display: flex;align-items: center;
}
.avatar {border-radius: 50%;margin-right: 10px;width: 50px;height: 50px;
}
.input-field {flex: 1;margin-right: 10px;max-width: calc(100% - 100px);
}
.message-content {max-width: 100%; /* 确保消息内容框不超过聊天框宽度 */background-color: #f0f0f0; /* 随意选择背景颜色 */border-radius: 5px; /* 圆角 */padding: 10px; /* 内边距 */overflow-wrap: break-word; /* 使长文本换行 */white-space: normal; /* 允许文本在标签内换行 */word-wrap: break-word; /* 兼容旧版浏览器 */
}
.user-message-content {background-color: #d1e7dd; /* 用户消息的背景颜色 */
}
.bot-message-content {background-color: #cfe2ff; /* 机器人消息的背景颜色 */
}
</style>
完成一个简单前端聊天界面的开发了!
这篇关于vue 实现简单AI聊天程序(一) elementui 聊天框编写的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!