Vue.js 实现 ChatGPT 聊天界面 - 代码示例
<p>"<template>\n <div>\n <div v-for="message in messages" :key="message.id" class="message">\n <span :class="message.type">{{ message.content }}</span>\n </div>\n <div class="input-container">\n <input v-model="inputMessage" @keydown.enter="sendMessage" type="text" placeholder="输入消息..." />\n <button @click="sendMessage">发送</button>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n messages: [],\n inputMessage: '',\n };\n },\n methods: {\n sendMessage() {\n if (this.inputMessage.trim() !== '') {\n this.messages.push({ id: Date.now(), content: this.inputMessage, type: 'user' });\n this.inputMessage = '';\n this.getChatGPTResponse();\n }\n },\n getChatGPTResponse() {\n // 发送用户输入消息到ChatGPT API并获取响应\n // 假设ChatGPT API的URL为 '/api/chatgpt'\n const apiUrl = '/api/chatgpt';\n fetch(apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ message: this.messages[this.messages.length - 1].content }),\n })\n .then(response => response.json())\n .then(data => {\n this.messages.push({ id: Date.now(), content: data.response, type: 'chatgpt' });\n })\n .catch(error => {\n console.error('Error:', error);\n });\n },\n },\n};\n</script>\n\n<style scoped>\n.message {\n margin: 10px;\n padding: 5px;\n border: 1px solid #ccc;\n border-radius: 5px;\n}\n\n.user {\n background-color: lightblue;\n}\n\n.chatgpt {\n background-color: lightgreen;\n}\n\n.input-container {\n display: flex;\n margin-top: 10px;\n}\n\ninput {\n flex: 1;\n padding: 5px;\n}\n\nbutton {\n padding: 5px 10px;\n}\n</style>\n"该代码通过使用<code>v-for</code>指令来循环渲染每条消息,并根据消息的类型(用户或ChatGPT)来应用不同的样式。用户可以在输入框中输入消息,按下回车键或点击发送按钮发送消息。发送消息后,将该消息添加到消息列表中,并调用<code>getChatGPTResponse</code>方法发送用户输入消息到ChatGPT API,然后将ChatGPT的响应添加到消息列表中。\n\n请注意,此代码仅为示例,实际实现中,你需要将ChatGPT API的URL和其他细节根据实际情况进行调整。</p>
原文地址: https://www.cveoy.top/t/topic/pNKp 著作权归作者所有。请勿转载和采集!