Files

960 lines
21 KiB
Markdown
Raw Permalink Normal View History

2026-02-03 12:11:57 +08:00
# 任务 10:前端项目初始化
## 任务概述
初始化 Vue 3 前端项目,配置路由、状态管理、UI 组件库等基础设施。
## 前置条件
- 任务 01-09 已完成
- 后端 API 已实现
## 任务目标
- 配置 Vue Router
- 配置 Pinia 状态管理
- 配置 Element Plus
- 创建基础布局
- 配置 API 请求
- 实现登录页面(预留)
## 详细步骤
### 1. 配置路由
创建 `frontend/src/router/index.ts`:
```typescript
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
{
path: '/',
redirect: '/dashboard',
},
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { title: '仪表盘' },
},
{
path: '/config',
name: 'Config',
redirect: '/config/llm',
meta: { title: '配置管理' },
children: [
{
path: 'llm',
name: 'LlmConfig',
component: () => import('@/views/config/LlmConfig.vue'),
meta: { title: 'LLM 配置' },
},
{
path: 'sources',
name: 'Sources',
component: () => import('@/views/config/Sources.vue'),
meta: { title: '数据源管理' },
},
{
path: 'channels',
name: 'Channels',
component: () => import('@/views/config/Channels.vue'),
meta: { title: '推送渠道' },
},
{
path: 'topics',
name: 'Topics',
component: () => import('@/views/config/Topics.vue'),
meta: { title: '主题管理' },
},
],
},
{
path: '/reports',
name: 'Reports',
component: () => import('@/views/reports/ReportList.vue'),
meta: { title: '报告中心' },
},
{
path: '/reports/:id',
name: 'ReportDetail',
component: () => import('@/views/reports/ReportDetail.vue'),
meta: { title: '报告详情' },
},
{
path: '/articles',
name: 'Articles',
component: () => import('@/views/articles/ArticleList.vue'),
meta: { title: '资讯浏览' },
},
{
path: '/monitoring',
name: 'Monitoring',
component: () => import('@/views/monitoring/Monitoring.vue'),
meta: { title: '采集监控' },
},
]
const router = createRouter({
history: createWebHistory(),
routes,
})
// 路由守卫
router.beforeEach((to, from, next) => {
// 设置页面标题
if (to.meta.title) {
document.title = `${to.meta.title} - News Aggregator`
}
next()
})
export default router
```
### 2. 配置 Pinia 状态管理
创建 `frontend/src/stores/app.ts`:
```typescript
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useAppStore = defineStore('app', () => {
// 侧边栏折叠状态
const sidebarCollapsed = ref(false)
// 切换侧边栏
const toggleSidebar = () => {
sidebarCollapsed.value = !sidebarCollapsed.value
}
return {
sidebarCollapsed,
toggleSidebar,
}
})
```
创建 `frontend/src/stores/user.ts`:
```typescript
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user', () => {
const token = ref<string | null>(null)
const userInfo = ref<any>(null)
const setToken = (newToken: string) => {
token.value = newToken
localStorage.setItem('token', newToken)
}
const setUserInfo = (info: any) => {
userInfo.value = info
}
const logout = () => {
token.value = null
userInfo.value = null
localStorage.removeItem('token')
}
// 初始化时从 localStorage 恢复 token
const initToken = () => {
const savedToken = localStorage.getItem('token')
if (savedToken) {
token.value = savedToken
}
}
return {
token,
userInfo,
setToken,
setUserInfo,
logout,
initToken,
}
})
```
### 3. 配置 API 请求
创建 `frontend/src/api/request.ts`:
```typescript
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
// 创建 axios 实例
const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
timeout: 30000,
})
// 请求拦截器
service.interceptors.request.use(
(config) => {
const userStore = useUserStore()
if (userStore.token) {
config.headers.Authorization = `Bearer ${userStore.token}`
}
return config
},
(error) => {
console.error('Request error:', error)
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
(response: AxiosResponse) => {
const res = response.data
// 如果响应格式不是标准格式,直接返回
if (res.success === undefined) {
return res
}
// 处理业务错误
if (!res.success) {
ElMessage.error(res.error?.message || '请求失败')
return Promise.reject(new Error(res.error?.message || '请求失败'))
}
return res.data
},
(error) => {
console.error('Response error:', error)
// 处理 HTTP 错误
if (error.response) {
const status = error.response.status
switch (status) {
case 401:
ElMessage.error('未授权,请登录')
// 跳转到登录页
break
case 403:
ElMessage.error('拒绝访问')
break
case 404:
ElMessage.error('请求的资源不存在')
break
case 500:
ElMessage.error('服务器错误')
break
default:
ElMessage.error(error.response.data?.error?.message || '请求失败')
}
} else if (error.request) {
ElMessage.error('网络错误,请检查网络连接')
} else {
ElMessage.error('请求配置错误')
}
return Promise.reject(error)
}
)
export default service
```
创建 `frontend/src/api/types.ts`:
```typescript
// 分页参数
export interface PaginationParams {
page?: number
limit?: number
}
// 分页响应
export interface PaginatedResponse<T> {
items: T[]
total: number
page: number
limit: number
totalPages: number
}
// LLM 配置
export interface LlmConfig {
id: number
name: string
baseUrl: string
model: string
apiKey: string
enabled: boolean
createdAt: string
updatedAt: string
}
// 数据源
export interface Source {
id: number
name: string
type: 'api' | 'playwright' | 'rss'
config: any
cronExpression: string
enabled: boolean
lastCollectedAt: string | null
createdAt: string
updatedAt: string
}
// 推送渠道
export interface Channel {
id: number
name: string
type: 'email' | 'dingtalk' | 'wechat' | 'slack'
config: any
enabled: boolean
createdAt: string
updatedAt: string
}
// 主题
export interface Topic {
id: number
name: string
description: string | null
processMode: 'aggregate' | 'summary' | 'deep_analysis'
llmConfigId: number | null
scheduleConfig: any
enabled: boolean
createdAt: string
updatedAt: string
llmConfig?: LlmConfig
topicSources?: Array<{ source: Source }>
topicChannels?: Array<{ channel: Channel }>
}
// 报告
export interface Report {
id: number
topicId: number
title: string
content: string
periodStart: string
periodEnd: string
status: 'pending' | 'generating' | 'completed' | 'failed'
errorMessage: string | null
articleCount: number
createdAt: string
updatedAt: string
topic?: Topic
}
// 资讯
export interface Article {
id: number
sourceId: number
title: string
content: string | null
summary: string | null
url: string | null
publishedAt: string | null
collectedAt: string
createdAt: string
source?: Source
}
// 采集日志
export interface CollectionLog {
id: number
sourceId: number
status: 'success' | 'failed'
errorMessage: string | null
articlesCount: number
startedAt: string
finishedAt: string | null
durationMs: number | null
createdAt: string
source?: Source
}
```
### 4. 创建基础布局
创建 `frontend/src/layouts/MainLayout.vue`:
```vue
<template>
<el-container class="main-layout">
<!-- 侧边栏 -->
<el-aside :width="sidebarWidth">
<div class="logo">
<h2 v-if="!appStore.sidebarCollapsed">News Aggregator</h2>
<h2 v-else>NA</h2>
</div>
<el-menu
:default-active="activeMenu"
:collapse="appStore.sidebarCollapsed"
router
>
<el-menu-item index="/dashboard">
<el-icon><HomeFilled /></el-icon>
<template #title>仪表盘</template>
</el-menu-item>
<el-sub-menu index="/config">
<template #title>
<el-icon><Setting /></el-icon>
<span>配置管理</span>
</template>
<el-menu-item index="/config/llm">LLM 配置</el-menu-item>
<el-menu-item index="/config/sources">数据源</el-menu-item>
<el-menu-item index="/config/channels">推送渠道</el-menu-item>
<el-menu-item index="/config/topics">主题</el-menu-item>
</el-sub-menu>
<el-menu-item index="/reports">
<el-icon><Document /></el-icon>
<template #title>报告中心</template>
</el-menu-item>
<el-menu-item index="/articles">
<el-icon><Reading /></el-icon>
<template #title>资讯浏览</template>
</el-menu-item>
<el-menu-item index="/monitoring">
<el-icon><Monitor /></el-icon>
<template #title>采集监控</template>
</el-menu-item>
</el-menu>
</el-aside>
<!-- 主内容区 -->
<el-container>
<!-- 顶部栏 -->
<el-header>
<div class="header-left">
<el-button
:icon="appStore.sidebarCollapsed ? Expand : Fold"
@click="appStore.toggleSidebar"
/>
<el-breadcrumb separator="/">
<el-breadcrumb-item
v-for="item in breadcrumbs"
:key="item.path"
:to="item.path"
>
{{ item.title }}
</el-breadcrumb-item>
</el-breadcrumb>
</div>
<div class="header-right">
<!-- 预留用户信息 -->
</div>
</el-header>
<!-- 内容区 -->
<el-main>
<router-view />
</el-main>
</el-container>
</el-container>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAppStore } from '@/stores/app'
import {
HomeFilled,
Setting,
Document,
Reading,
Monitor,
Expand,
Fold,
} from '@element-plus/icons-vue'
const route = useRoute()
const appStore = useAppStore()
const sidebarWidth = computed(() => {
return appStore.sidebarCollapsed ? '64px' : '200px'
})
const activeMenu = computed(() => {
return route.path
})
const breadcrumbs = computed(() => {
const matched = route.matched.filter((item) => item.meta?.title)
return matched.map((item) => ({
path: item.path,
title: item.meta.title as string,
}))
})
</script>
<style scoped>
.main-layout {
height: 100vh;
}
.el-aside {
background-color: #304156;
transition: width 0.3s;
}
.logo {
height: 60px;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 20px;
font-weight: bold;
}
.el-menu {
border-right: none;
background-color: #304156;
}
.el-header {
display: flex;
align-items: center;
justify-content: space-between;
background-color: #fff;
border-bottom: 1px solid #e6e6e6;
padding: 0 20px;
}
.header-left {
display: flex;
align-items: center;
gap: 20px;
}
.el-main {
background-color: #f0f2f5;
padding: 20px;
}
</style>
```
### 5. 创建仪表盘页面
创建 `frontend/src/views/Dashboard.vue`:
```vue
<template>
<div class="dashboard">
<el-row :gutter="20">
<el-col :span="6">
<el-card>
<template #header>
<div class="card-header">
<span>数据源</span>
</div>
</template>
<div class="stat-item">
<div class="stat-value">{{ stats.sources }}</div>
<div class="stat-label">总数</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card>
<template #header>
<div class="card-header">
<span>主题</span>
</div>
</template>
<div class="stat-item">
<div class="stat-value">{{ stats.topics }}</div>
<div class="stat-label">总数</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card>
<template #header>
<div class="card-header">
<span>报告</span>
</div>
</template>
<div class="stat-item">
<div class="stat-value">{{ stats.reports }}</div>
<div class="stat-label">总数</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card>
<template #header>
<div class="card-header">
<span>资讯</span>
</div>
</template>
<div class="stat-item">
<div class="stat-value">{{ stats.articles }}</div>
<div class="stat-label">总数</div>
</div>
</el-card>
</el-col>
</el-row>
<el-row :gutter="20" style="margin-top: 20px">
<el-col :span="12">
<el-card>
<template #header>
<div class="card-header">
<span>最近报告</span>
<el-button type="primary" link @click="$router.push('/reports')">
查看更多
</el-button>
</div>
</template>
<el-empty v-if="recentReports.length === 0" description="暂无报告" />
<div v-else class="report-list">
<div
v-for="report in recentReports"
:key="report.id"
class="report-item"
@click="$router.push(`/reports/${report.id}`)"
>
<div class="report-title">{{ report.title }}</div>
<div class="report-meta">
<el-tag :type="getStatusType(report.status)" size="small">
{{ getStatusText(report.status) }}
</el-tag>
<span class="report-time">
{{ formatTime(report.createdAt) }}
</span>
</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="12">
<el-card>
<template #header>
<div class="card-header">
<span>采集状态</span>
<el-button type="primary" link @click="$router.push('/monitoring')">
查看详情
</el-button>
</div>
</template>
<el-empty v-if="collectionStats.length === 0" description="暂无数据" />
<div v-else class="collection-list">
<div
v-for="stat in collectionStats"
:key="stat.id"
class="collection-item"
>
<div class="collection-name">{{ stat.name }}</div>
<div class="collection-meta">
<el-tag
:type="stat.lastLog?.status === 'success' ? 'success' : 'danger'"
size="small"
>
{{ stat.lastLog?.status === 'success' ? '成功' : '失败' }}
</el-tag>
<span class="collection-time">
{{ formatTime(stat.lastCollectedAt) }}
</span>
</div>
</div>
</div>
</el-card>
</el-col>
</el-row>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/api/request'
import type { Report } from '@/api/types'
const stats = ref({
sources: 0,
topics: 0,
reports: 0,
articles: 0,
})
const recentReports = ref<Report[]>([])
const collectionStats = ref<any[]>([])
const loadStats = async () => {
try {
const [sourcesRes, topicsRes, reportsRes, articlesRes] = await Promise.all([
request.get('/sources', { params: { limit: 1 } }),
request.get('/topics', { params: { limit: 1 } }),
request.get('/reports', { params: { limit: 1 } }),
request.get('/articles', { params: { limit: 1 } }),
])
stats.value = {
sources: sourcesRes.total || 0,
topics: topicsRes.total || 0,
reports: reportsRes.total || 0,
articles: articlesRes.total || 0,
}
} catch (error) {
ElMessage.error('加载统计数据失败')
}
}
const loadRecentReports = async () => {
try {
const res = await request.get('/reports', { params: { limit: 5 } })
recentReports.value = res.items || []
} catch (error) {
ElMessage.error('加载最近报告失败')
}
}
const loadCollectionStats = async () => {
try {
const res = await request.get('/collection-logs/stats')
collectionStats.value = res.slice(0, 5)
} catch (error) {
ElMessage.error('加载采集状态失败')
}
}
const getStatusType = (status: string) => {
const map: Record<string, any> = {
pending: 'info',
generating: 'warning',
completed: 'success',
failed: 'danger',
}
return map[status] || 'info'
}
const getStatusText = (status: string) => {
const map: Record<string, string> = {
pending: '待处理',
generating: '生成中',
completed: '已完成',
failed: '失败',
}
return map[status] || status
}
const formatTime = (time: string | null) => {
if (!time) return '未知'
return new Date(time).toLocaleString('zh-CN')
}
onMounted(() => {
loadStats()
loadRecentReports()
loadCollectionStats()
})
</script>
<style scoped>
.dashboard {
/* 样式 */
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.stat-item {
text-align: center;
padding: 20px 0;
}
.stat-value {
font-size: 32px;
font-weight: bold;
color: #409eff;
}
.stat-label {
margin-top: 10px;
color: #909399;
}
.report-list,
.collection-list {
/* 样式 */
}
.report-item,
.collection-item {
padding: 12px;
border-bottom: 1px solid #ebeef5;
cursor: pointer;
}
.report-item:hover,
.collection-item:hover {
background-color: #f5f7fa;
}
.report-title,
.collection-name {
font-weight: 500;
margin-bottom: 8px;
}
.report-meta,
.collection-meta {
display: flex;
align-items: center;
gap: 10px;
font-size: 12px;
color: #909399;
}
</style>
```
### 6. 更新 App.vue
更新 `frontend/src/App.vue`:
```vue
<template>
<MainLayout />
</template>
<script setup lang="ts">
import MainLayout from '@/layouts/MainLayout.vue'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
userStore.initToken()
</script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#app {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}
</style>
```
### 7. 配置环境变量
创建 `frontend/.env.development`:
```env
VITE_API_BASE_URL=http://localhost:3000/api
```
创建 `frontend/.env.production`:
```env
VITE_API_BASE_URL=/api
```
### 8. 创建占位页面
创建空的页面组件(后续任务中实现):
```bash
mkdir -p src/views/config
mkdir -p src/views/reports
mkdir -p src/views/articles
mkdir -p src/views/monitoring
# 创建占位文件
touch src/views/config/LlmConfig.vue
touch src/views/config/Sources.vue
touch src/views/config/Channels.vue
touch src/views/config/Topics.vue
touch src/views/reports/ReportList.vue
touch src/views/reports/ReportDetail.vue
touch src/views/articles/ArticleList.vue
touch src/views/monitoring/Monitoring.vue
```
每个文件添加基本内容:
```vue
<template>
<div>
<h1>页面标题</h1>
<p>此页面将在后续任务中实现</p>
</div>
</template>
<script setup lang="ts">
// 待实现
</script>
```
## 验证步骤
### 1. 启动前端开发服务器
```bash
cd frontend
npm run dev
```
### 2. 访问应用
打开浏览器访问 http://localhost:5173
### 3. 验证功能
- ✅ 页面正常加载
- ✅ 侧边栏可以折叠/展开
- ✅ 路由导航正常
- ✅ 仪表盘显示统计数据
- ✅ Element Plus 组件正常显示
### 4. 测试 API 请求
打开浏览器开发者工具,检查:
- Network 标签中有 API 请求
- 请求地址正确(http://localhost:3000/api/...)
- 响应数据正常
## 预期产物
- ✅ Vue Router 配置完成
- ✅ Pinia 状态管理配置完成
- ✅ Element Plus 配置完成
- ✅ API 请求封装完成
- ✅ 基础布局实现完成
- ✅ 仪表盘页面实现完成
- ✅ 路由导航正常工作
- ✅ 前端可以正常访问后端 API
## 常见问题
### 问题 1:API 请求 CORS 错误
**解决方案**:确保后端已配置 CORS,允许前端域名访问。
### 问题 2:路由 404
**解决方案**:检查路由配置,确保组件路径正确。
### 问题 3:Element Plus 样式不生效
**解决方案**:检查是否正确导入 Element Plus 样式文件。
## 下一步
完成本任务后,继续 [任务 11:前端配置管理](./11-frontend-config.md)。