从 0 到 1:开发一个现代炫酷的 AI 聊天页面

引言:

在现代 Web 应用中,聊天页面已经成为了一个非常常见的功能,尤其是随着 AI 技术的普及,接入 AI 聊天功能的需求越来越多。今天,我将带你从 0 到 1 开发一个现代、炫酷的聊天页面,支持与 AI 进行实时对话。我们将使用 Vue 3 和 Tailwind CSS 来实现这个功能,确保页面既美观又高效。


1. 功能需求

在开始之前,我们先明确一下这个聊天页面的核心功能:

  • 消息展示:支持显示用户和 AI 的对话消息。
  • 消息发送:用户可以输入消息并发送给 AI。
  • 实时响应:AI 能够实时回复用户的消息。
  • 界面美观:页面设计现代、炫酷,用户体验良好。

2. 技术选型

  • 前端框架:Vue 3(Composition API)
  • 样式库:Tailwind CSS(快速构建现代 UI)
  • AI 接口:假设我们有一个 AI 聊天接口(例如 OpenAI 的 GPT 模型)。
  • 图标库 :使用 Heroicons 提供图标支持。

3. 项目结构

bash 复制代码
/src
|-- assets/            # 静态资源
|-- components/        # 组件
|   |-- Message.vue    # 单条消息组件
|-- views/             # 页面
|   |-- ChatView.vue   # 聊天页面
|-- App.vue            # 根组件
|-- main.js            # 入口文件

4. 代码实现

4.1 安装依赖

首先,确保安装了 Vue 3 和 Tailwind CSS:

bash 复制代码
npm install vue@next
npm install tailwindcss postcss autoprefixer
npx tailwindcss init
4.2 配置 Tailwind CSS

tailwind.config.js 中配置:

javascript 复制代码
module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

src/assets/css/tailwind.css 中引入 Tailwind:

css 复制代码
@tailwind base;
@tailwind components;
@tailwind utilities;
4.3 实现聊天页面
ChatView.vue
html 复制代码
<template>
  <div class="flex flex-col h-screen bg-gray-900 text-white">
    <!-- 聊天消息区域 -->
    <div class="flex-1 p-6 overflow-y-auto">
      <div v-for="(message, index) in messages" :key="index" class="mb-4">
        <Message :message="message" />
      </div>
    </div>

    <!-- 输入框 -->
    <div class="p-4 bg-gray-800">
      <div class="flex items-center">
        <input
          v-model="inputText"
          @keyup.enter="sendMessage"
          class="flex-1 p-2 rounded-lg bg-gray-700 text-white focus:outline-none"
          placeholder="输入消息..."
        />
        <button
          @click="sendMessage"
          class="ml-4 p-2 bg-blue-500 rounded-lg hover:bg-blue-600 transition-colors"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="h-6 w-6"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
            />
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Message from '@/components/Message.vue';

const messages = ref([
  { text: '你好!我是 AI 助手,有什么可以帮你的吗?', isUser: false },
]);

const inputText = ref('');

const sendMessage = async () => {
  if (!inputText.value.trim()) return;

  // 添加用户消息
  messages.value.push({ text: inputText.value, isUser: true });
  const userMessage = inputText.value;
  inputText.value = '';

  // 模拟 AI 回复
  const aiResponse = await fetchAIResponse(userMessage);
  messages.value.push({ text: aiResponse, isUser: false });
};

const fetchAIResponse = async (message) => {
  // 这里调用 AI 接口
  // 假设我们有一个模拟的 AI 回复
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`你刚刚说的是:"${message}"`);
    }, 1000);
  });
};
</script>
Message.vue
html 复制代码
<template>
  <div :class="['flex', message.isUser ? 'justify-end' : 'justify-start']">
    <div
      :class="[
        'max-w-[70%] p-3 rounded-lg',
        message.isUser ? 'bg-blue-500 text-white' : 'bg-gray-700 text-white',
      ]"
    >
      {{ message.text }}
    </div>
  </div>
</template>

<script setup>
defineProps({
  message: {
    type: Object,
    required: true,
  },
});
</script>

5. 运行效果

  1. 消息展示

    • 用户消息显示在右侧,AI 消息显示在左侧。
    • 每条消息都有不同的背景色,区分用户和 AI。
  2. 消息发送

    • 用户可以在输入框中输入消息,按下回车或点击按钮发送。
    • 发送后,输入框清空,消息立即显示在聊天区域。
  3. AI 回复

    • 模拟 AI 回复,1 秒后显示回复内容。
  4. 界面美观

    • 使用 Tailwind CSS 实现现代设计,背景为深色主题,消息气泡圆角设计。

6. 接入真实 AI 接口

如果你有一个真实的 AI 聊天接口(例如 OpenAI 的 GPT 模型),可以在 fetchAIResponse 方法中调用接口:

javascript 复制代码
const fetchAIResponse = async (message) => {
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer YOUR_API_KEY`,
    },
    body: JSON.stringify({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: message }],
    }),
  });
  const data = await response.json();
  return data.choices[0].message.content;
};

7. 总结

通过 Vue 3 和 Tailwind CSS,我们快速实现了一个现代、炫酷的 AI 聊天页面。这个页面不仅功能完善,而且界面美观,用户体验良好。如果你有真实的 AI 接口,可以轻松接入,实现更强大的功能。

希望这篇文章对你有帮助!如果你有任何问题或建议,欢迎在评论区留言。别忘了点赞、转发、打赏!你的支持是我持续分享的动力!


互动话题:

你在开发聊天页面时遇到过哪些问题?你是如何解决的?欢迎分享你的经验!

相关推荐
Rowrey1 小时前
react+typescript,初始化与项目配置
javascript·react.js·typescript
谢尔登1 小时前
Vue 和 React 的异同点
前端·vue.js·react.js
祈澈菇凉5 小时前
Webpack的基本功能有哪些
前端·javascript·vue.js
小纯洁w5 小时前
Webpack 的 require.context 和 Vite 的 import.meta.glob 的详细介绍和使用
前端·webpack·node.js
想睡好6 小时前
css文本属性
前端·css
qianmoQ6 小时前
第三章:组件开发实战 - 第五节 - Tailwind CSS 响应式导航栏实现
前端·css
记得早睡~6 小时前
leetcode150-逆波兰表达式求值
javascript·算法·leetcode
zhoupenghui1686 小时前
golang时间相关函数总结
服务器·前端·golang·time
White graces6 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
庸俗今天不摸鱼6 小时前
Canvas进阶-4、边界检测(流光,鼠标拖尾)
开发语言·前端·javascript·计算机外设