很多前端开发者在接入 AI 能力时,常对参数传递、流式响应处理感到困惑。其实流程是固定的,本文以'智能文本处理工具'为例,带你梳理从项目配置到 Vue 组件集成的完整链路。
项目结构梳理
核心依赖三个文件:vite.config.js 负责代理转发,apiClient.js 封装请求逻辑,aiService.js 提供具体业务函数。
1. 跨域代理配置 (vite.config.js)
Vite 开发环境下,直接请求后端容易触发跨域。通过配置代理,将 /writer_api 开头的请求自动转发到目标服务器。
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
server: {
proxy: {
// AI 功能接口代理(润色/扩写等)
'/writer_api': {
target: 'http://192.168.0.1:3000', // 后端服务器地址
changeOrigin: true, // 解决跨域
rewrite: path => path.replace(/^\/writer_api/, '') // 去掉前缀
}
}
}
});
2. 请求工具封装 (apiClient.js)
不需要每次重复写 fetch 细节,封装一个 HTTP 客户端即可。这里使用原生 Fetch API,保持轻量。
// apiClient.js
class HttpClient {
async post(url, data) {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
}
}
export default new HttpClient();
3. AI 功能封装 (aiService.js)
这里定义了具体的业务方法,包括流式响应的处理逻辑。AI 生成内容通常是逐字返回的,我们需要实时读取流并更新 UI。
// aiService.js
import apiClient from './apiClient.js';
// 润色功能
export const polishText = async (text, style) => {
return apiClient.post('/writer_api/generate/', {
writing_mode: `润色${style}`,
text: text
});
};
// 扩写功能
export const expandText = async (text) => {
return apiClient.post('/writer_api/generate/', {
writing_mode: '扩写',
text: text
});
};
// 处理流式响应(AI 逐字返回结果时用)
export const readStreamResponse = async (response, onUpdate) => {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let result = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
result += decoder.decode(value);
onUpdate(result); // 实时更新结果
}
return result;
};
动手实践:Vue 组件集成
接下来我们构建一个简单的页面,包含输入框、功能按钮和结果展示区。
页面结构与逻辑
在 Vue 组件中,我们将上述服务函数引入,并通过异步函数绑定点击事件。注意处理用户输入校验和异常捕获。
<template>
<div class="ai-tool">
<!-- 输入区域 -->
<textarea v-model="userText" placeholder="请输入需要处理的文本..."></textarea>
<!-- 功能按钮 -->
<div class="buttons">
<button @click="handlePolish">润色</button>
<button @click="handleExpand">扩写</button>
</div>
<!-- 结果展示 -->
<div class="result">
<h3>处理结果:</h3>
<p>{{ resultText }}</p>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { polishText, expandText, readStreamResponse } from './aiService.js';
const userText = ref('');
const resultText = ref('');
// 1. 调用润色功能
const handlePolish = async () => {
if (!userText.value) {
alert('请输入文本!');
return;
}
try {
const response = await polishText(userText.value, '更正式');
await readStreamResponse(response, (partialResult) => {
resultText.value = partialResult; // 实时显示到页面
});
} catch (error) {
alert('润色失败,请重试!');
console.error(error);
}
};
// 2. 调用扩写功能
const handleExpand = async () => {
if (!userText.value) {
alert('请输入文本!');
return;
}
try {
const response = await expandText(userText.value);
await readStreamResponse(response, (partialResult) => {
resultText.value = partialResult;
});
} catch (error) {
alert('扩写失败,请重试!');
}
};
</script>
<style scoped>
.ai-tool {
max-width: 800px;
margin: 20px auto;
padding: 20px;
}
textarea {
width: 100%;
height: 150px;
padding: 10px;
margin-bottom: 10px;
}
.buttons {
margin-bottom: 20px;
}
button {
margin-right: 10px;
padding: 8px 16px;
cursor: pointer;
}
.result {
padding: 10px;
border: 1px solid #eee;
}
</style>
关键步骤总结
不管调用哪种 AI 功能,核心链路是一致的:
- 获取输入:确保用户已填写内容。
- 调用接口:根据需求选择
polishText或expandText。 - 流式处理:利用
readStreamResponse实现打字机效果,提升体验。 - 异常捕获:用
try/catch包裹异步操作,防止页面卡死。
常见问题与扩展
- 为什么要处理流式响应? AI 生成内容是逐字返回的,流式处理能让用户实时看到进度,避免长时间等待白屏。
- 想加翻译功能怎么办?
在
aiService.js中添加translateText函数,并在页面增加对应按钮,逻辑复用扩写部分。 - 后端接口地址变了怎么办?
只需修改
vite.config.js中的target地址,无需改动业务代码。
调用 AI 接口本质就是'传参→接收流→渲染'。掌握这套模式后,无论是润色、扩写还是其他功能,都能快速接入。

