1. 创建 Vue.js 项目
如果你还没有 Vue.js 项目,可以使用 Vue CLI 快速创建一个新项目:
npm install -g @vue/cli vue create deepseek-api-demo cd deepseek-api-demo
复制
选择默认配置或手动选择需要的特性(如 Vue 3、TypeScript 等)。
2. 安装必要的依赖
你需要安装 axios
来发送 HTTP 请求:
npm install axios
复制
3. 创建 API 服务文件
在 src
目录下创建一个 api
文件夹,并在其中创建一个 deepseekApi.js
文件,用于封装与 DeepSeek API 的交互。
// src/api/deepseekApi.js import axios from 'axios'; const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1'; // 替换为实际的 DeepSeek API URL const DEEPSEEK_API_KEY = 'your-api-key'; // 替换为你的 API Key const deepseekApi = { // 示例:获取某个资源 getResource: async (resourceId) => { try { const response = await axios.get(`${DEEPSEEK_API_URL}/resources/${resourceId}`, { headers: { Authorization: `Bearer ${DEEPSEEK_API_KEY}`, }, }); return response.data; } catch (error) { console.error('Error fetching resource:', error); throw error; } }, // 示例:创建某个资源 createResource: async (resourceData) => { try { const response = await axios.post(`${DEEPSEEK_API_URL}/resources`, resourceData, { headers: { Authorization: `Bearer ${DEEPSEEK_API_KEY}`, }, }); return response.data; } catch (error) { console.error('Error creating resource:', error); throw error; } }, // 其他 API 调用... }; export default deepseekApi;
复制
4. 在 Vue 组件中使用 API
你可以在 Vue 组件中使用 deepseekApi
来调用 DeepSeek API。例如,在 src/components/ResourceView.vue
中:
<template>
<div>
<h1>DeepSeek Resource</h1>
<div v-if="loading">Loading...</div>
<div v-else-if="error">Error: {{ error }}</div>
<div v-else>
<h2>{{ resource.name }}</h2>
<p>{{ resource.description }}</p>
</div>
</div>
</template>
<script>
import deepseekApi from '@/api/deepseekApi';
export default {
data() {
return {
resource: null,
loading: true,
error: null,
};
},
async created() {
try {
const resourceId = '123'; // 替换为实际的资源 ID
const data = await deepseekApi.getResource(resourceId);
this.resource = data;
} catch (err) {
this.error = err.message;
} finally {
this.loading = false;
}
},
};
</script>
<style scoped>
/* 添加样式 */
</style>
复制
5. 在主组件中引入并使用
在 src/App.vue
中引入并使用 ResourceView
组件:
<template>
<div id="app">
<ResourceView />
</div>
</template>
<script>
import ResourceView from './components/ResourceView.vue';
export default {
name: 'App',
components: {
ResourceView,
},
};
</script>
<style>
/* 全局样式 */
</style>
复制
6. 运行项目
确保你的 Vue.js 项目正在运行:
npm run serve
复制
打开浏览器,访问 http://localhost:8080
,查看你的应用是否正常工作。
7. 处理 API 认证
如果 DeepSeek API 需要认证(如 API Key 或 OAuth),你需要在请求头中添加认证信息。例如:
const response = await axios.get(`${DEEPSEEK_API_URL}/resources/${resourceId}`, { headers: { Authorization: `Bearer ${DEEPSEEK_API_KEY}`, }, });
复制
8. 测试和调试
使用浏览器的开发者工具或 console.log
进行调试,确保 API 调用正常工作。
9. 部署
当你完成开发并测试通过后,可以使用以下命令构建生产版本:
npm run build
复制
然后将 dist
目录中的文件部署到你的服务器或静态网站托管服务上。