<p>&quot;<template>\n  <div>\n    &lt;div v-for=&quot;message in messages&quot; :key=&quot;message.id&quot; class=&quot;message&quot;&gt;\n      &lt;span :class=&quot;message.type&quot;&gt;{{ message.content }}</span>\n    </div>\n    &lt;div class=&quot;input-container&quot;&gt;\n      &lt;input v-model=&quot;inputMessage&quot; @keydown.enter=&quot;sendMessage&quot; type=&quot;text&quot; placeholder=&quot;输入消息...&quot; /&gt;\n      &lt;button @click=&quot;sendMessage&quot;&gt;发送</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 =&gt; response.json())\n        .then(data =&gt; {\n          this.messages.push({ id: Date.now(), content: data.response, type: 'chatgpt' });\n        })\n        .catch(error =&gt; {\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&quot;该代码通过使用<code>v-for</code>指令来循环渲染每条消息,并根据消息的类型(用户或ChatGPT)来应用不同的样式。用户可以在输入框中输入消息,按下回车键或点击发送按钮发送消息。发送消息后,将该消息添加到消息列表中,并调用<code>getChatGPTResponse</code>方法发送用户输入消息到ChatGPT API,然后将ChatGPT的响应添加到消息列表中。\n\n请注意,此代码仅为示例,实际实现中,你需要将ChatGPT API的URL和其他细节根据实际情况进行调整。</p>
Vue.js 实现 ChatGPT 聊天界面 - 代码示例

原文地址: https://www.cveoy.top/t/topic/pNKp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录