AI原生前端开发(017):端侧AI与Vue 3结合实战

前言

上一篇学了React,这一篇我们学习Vue 3 + 端侧AI!


1. 创建Vue Composables

javascript 复制代码
// ai.js
import { ref, computed } from 'vue';

export function useAI() {
  const isReady = ref(false);
  const isLoading = ref(false);
  const error = ref(null);
  const session = ref(null);

  async function initAI(options = {}) {
    try {
      isLoading.value = true;
      error.value = null;

      if (!('ai' in window)) {
        throw new Error('浏览器不支持Chrome AI');
      }

      session.value = await window.ai.assistant.create({
        systemPrompt: options.systemPrompt || '你是一个AI助手。',
        temperature: options.temperature || 0.7
      });

      isReady.value = true;
    } catch (err) {
      error.value = err.message;
    } finally {
      isLoading.value = false;
    }
  }

  async function sendMessage(prompt) {
    if (!session.value) {
      throw new Error('AI未初始化');
    }
    return await session.value.prompt(prompt);
  }

  async function* sendMessageStream(prompt) {
    if (!session.value) {
      throw new Error('AI未初始化');
    }
    const stream = session.value.promptStreaming(prompt);
    for await (const chunk of stream) {
      yield chunk;
    }
  }

  function destroy() {
    if (session.value) {
      session.value.destroy();
      session.value = null;
      isReady.value = false;
    }
  }

  return {
    isReady,
    isLoading,
    error,
    initAI,
    sendMessage,
    sendMessageStream,
    destroy
  };
}

2. Vue AI聊天组件

vue 复制代码
<template>
  <div class="max-w-3xl mx-auto p-6 h-screen flex flex-col">
    <h1 class="text-2xl font-bold mb-6">🤖 AI聊天 (Vue版)</h1>
    
    <div class="flex-1 overflow-y-auto space-y-4 mb-6">
      <div v-if="messages.length === 0" class="text-center py-12 text-gray-500">
        开始和AI聊天吧!
      </div>
      
      <div 
        v-for="(msg, index) in messages" 
        :key="msg.id || index"
        :class="[
          'p-4 rounded-lg max-w-[80%]',
          msg.role === 'user' ? 'ml-auto bg-blue-600 text-white' : 'bg-gray-100'
        ]"
      >
        <p>{{ msg.content }}</p>
      </div>
      
      <div v-if="isGenerating" class="p-4 bg-gray-100 rounded-lg max-w-[80%]">
        <div class="flex gap-2">
          <span class="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></span>
          <span class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></span>
          <span class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></span>
        </div>
      </div>
      
      <div ref="messagesEndRef"></div>
    </div>
    
    <div class="flex gap-2">
      <input
        v-model="input"
        @keydown.enter="handleSend"
        :disabled="!isReady || isGenerating"
        placeholder="输入消息..."
        class="flex-1 p-3 border rounded-lg disabled:opacity-50"
      />
      <button
        @click="handleSend"
        :disabled="!input.trim() || !isReady || isGenerating"
        class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
      >
        发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue';
import { useAI } from './ai';

const { isReady, initAI, sendMessageStream } = useAI();

const messages = ref([]);
const input = ref('');
const isGenerating = ref(false);
const messagesEndRef = ref(null);

onMounted(async () => {
  if (!isReady.value) {
    await initAI({
      systemPrompt: '你是一个友好的AI助手。用中文回答。'
    });
  }
});

watch(messages, async () => {
  await nextTick();
  messagesEndRef.value?.scrollIntoView({ behavior: 'smooth' });
});

async function handleSend() {
  if (!input.value.trim() || isGenerating.value || !isReady.value) return;

  // 添加用户消息
  const userMessage = { role: 'user', content: input.value };
  messages.value.push(userMessage);
  input.value = '';
  isGenerating.value = true;

  try {
    // 添加AI回复
    const aiMessageId = Date.now();
    messages.value.push({ role: 'assistant', content: '', id: aiMessageId });

    // 流式生成
    let fullContent = '';
    for await (const chunk of sendMessageStream(input.value)) {
      fullContent += chunk;
      const lastIndex = messages.value.length - 1;
      if (messages.value[lastIndex].id === aiMessageId) {
        messages.value[lastIndex].content = fullContent;
      }
    }

  } catch (error) {
    console.error('生成失败:', error);
  } finally {
    isGenerating.value = false;
  }
}
</script>

3. 今日小结

这一篇我们学习了:

  1. Vue Composables封装AI
  2. Vue AI聊天组件

4. 下篇预告

下一篇,我们学习 端侧AI性能优化!

相关推荐
treasure1401 小时前
【复古】浅尝Django前后端不分离
前端·css·python·django·bootstrap·html·web
老金带你玩AI1 小时前
惊人的一致性!Seedream 5.5实测!
人工智能
数据技术说2 小时前
在 KES AI 数据库上搭一条 NL2SQL 链路:语义、召回、权限各放哪
人工智能·sql·代码规范
jay神2 小时前
基于 YOLOv8 的手势识别系统(Web 版)
前端·人工智能·python·深度学习·yolo·计算机视觉·计算机毕业设计
屏什么录2 小时前
长时间录屏中途崩溃:MP4 打不开的 6 种救回方案与参数设置
前端·音视频开发
奶油话梅糖2 小时前
用 iPhone 扫一间房,AI 帮你在浏览器里 1:1 重建它:Wes Bos 的 scan-to-threejs 工作流
人工智能·ios·iphone
code_Bo2 小时前
不只命令行:我把跨 Agent 会话同步做成了桌面应用
前端·javascript·后端
锋行天下3 小时前
LangGraph HITL 实战:从 interrupt 到 useStream 的最小闭环
人工智能
kyriewen3 小时前
AI 能把页面写出来,为什么改个需求就开始崩?
前端·javascript·人工智能
张彦峰ZYF4 小时前
浏览器调试接口的官方化:从 chrome-devtools-mcp 看 Agent 原生工具层的形成
人工智能·chrome·agent·mcp·apache-2.0许可·devtools-mcp·调试闭环