web / docs /03-architecture.md
hanbinsite's picture
chore: initialize Nuxt web scaffold
2b5389d
|
Raw History Blame Contribute Delete
12.8 kB
# D03 - 架构设计
## 技术栈
| 层 | 技术 | 说明 |
|---|---|---|
| 框架 | Nuxt 3 | SSR + auto-import + Nitro server |
| UI组件 | Naive UI | 按需引入、暗色模式、轻量 |
| 样式 | Tailwind CSS 4 | 布局/响应式/动效 |
| 播放器 | ArtPlayer 5 + HLS插件 | M3U8播放 + iframe嵌入 |
| 语言 | TypeScript | 严格类型 |
| HTTP | ofetch (Nuxt内置) | useFetch / useAsyncData |
| 状态 | Pinia (nuxt-pinia) | 用户/播放状态 |
| 图标 | @iconify/vue | Lucide 图标集 |
| 部署 | Docker + Node.js | 自有服务器 |
## 目录结构
```
web/
├── nuxt.config.ts # Nuxt 配置
├── app.vue # 根组件
├── tailwind.config.ts # Tailwind 配置
├── tsconfig.json
├── package.json
├── Dockerfile # 生产部署
├── docker-compose.yml # 编排
├── .env # 环境变量
│
├── pages/ # 页面(文件路由)
│ ├── index.vue # 首页
│ ├── category/
│ │ └── [id].vue # 分类列表 (SSR)
│ ├── search.vue # 搜索结果
│ ├── vod/
│ │ └── [id].vue # 影片详情+播放 (SSR)
│ ├── login.vue # 登录
│ ├── register.vue # 注册
│ ├── favorite.vue # 收藏
│ └── history.vue # 播放历史
│
├── components/ # 组件
│ ├── VodCard.vue # 海报卡片
│ ├── VodGrid.vue # 卡片网格
│ ├── VodPlayer.vue # 播放器封装
│ ├── SourceSelector.vue # 多源切换
│ ├── EpisodeList.vue # 选集列表
│ ├── CategoryNav.vue # 分类导航
│ ├── SearchBar.vue # 搜索栏
│ ├── AppHeader.vue # 顶栏
│ ├── AppFooter.vue # 底栏
│ └── UserAvatar.vue # 用户头像/登录入口
│
├── composables/ # 组合式函数
│ ├── useAuth.ts # 用户鉴权 (login/logout/profile)
│ ├── usePlayer.ts # 播放器状态管理
│ ├── useApi.ts # API 请求封装
│ └── useInfiniteScroll.ts # 无限滚动
│
├── server/ # Nuxt Server
│ ├── api/
│ │ └── [...].ts # 代理到后端API
│ └── middleware/
│ └── auth.ts # 服务端鉴权
│
├── middleware/ # 客户端路由守卫
│ └── auth.ts # 需登录页面守卫
│
├── layouts/ # 布局
│ ├── default.vue # 带顶栏+底栏
│ └── blank.vue # 全屏(播放页可选)
│
├── stores/ # Pinia
│ ├── user.ts # 用户状态 (token/info)
│ └── player.ts # 播放状态 (当前源/集/进度)
│
├── assets/
│ └── css/
│ └── main.css # Tailwind 入口
│
├── public/
│ ├── favicon.ico
│ └── logo.svg
│
└── types/ # 全局类型
├── vod.ts
├── category.ts
├── user.ts
└── api.ts
```
## 分层架构
```
用户操作
│
▼
Nuxt Pages (pages/) ← 文件路由、SSR/CSR 自动选择
│
▼
Composables (composables/) ← 业务逻辑、状态组合
│
▼
Nuxt Server Proxy (server/api/) ← 代理到后端,避免跨域
│
▼
useFetch / useAsyncData ← 自动缓存、去重、SSR 数据获取
│
▼
BinV API (FastAPI :9999) ← 后端服务
```
## 数据获取策略
### SSR 页面
使用 `useAsyncData` + `useFetch`,服务端渲染时直接请求数据:
```typescript
// pages/vod/[id].vue
const route = useRoute();
const { data: vod } = await useAsyncData(
`vod-${route.params.id}`,
() => $fetch(`/api/user/vod/${route.params.id}`),
);
useHead({
title: () => `${vod.value?.name} - 在线播放 - BinV`,
meta: [
{ name: 'description', content: () => vod.value?.blurb?.slice(0, 100) || '' },
{ property: 'og:title', content: () => vod.value?.name || '' },
{ property: 'og:image', content: () => vod.value?.cover || '' },
],
});
```
### CSR 页面(收藏/历史/搜索)
使用 `useFetch` + 客户端加载:
```typescript
// pages/favorite.vue
const { data, pending } = await useFetch('/api/user/favorite', {
lazy: true,
headers: { Authorization: `Bearer ${token}` },
});
```
### Nuxt Server Proxy
```typescript
// server/api/[...].ts
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig();
const path = event.path.replace('/api/', '/user/');
return proxyRequest(event, `${config.apiBaseUrl}${path}`);
});
```
所有前端请求 `/api/user/*` → Nuxt server 代理 → `API_BASE_URL/user/*`
优势:
- 无跨域问题
- 隐藏后端真实地址
- 可在 server 端注入公共 header
## 请求层设计
### useApi composable
```typescript
// composables/useApi.ts
export function useApi() {
const userStore = useUserStore();
const config = useRuntimeConfig();
function getHeaders() {
const headers: Record<string, string> = {};
if (userStore.token) {
headers.Authorization = `Bearer ${userStore.token}`;
}
return headers;
}
async function get<T>(path: string, params?: Record<string, any>) {
return $fetch<T>(`${config.public.apiBase}${path}`, {
method: 'GET',
params,
headers: getHeaders(),
});
}
async function post<T>(path: string, body?: Record<string, any>) {
return $fetch<T>(`${config.public.apiBase}${path}`, {
method: 'POST',
body,
headers: getHeaders(),
});
}
async function del<T>(path: string) {
return $fetch<T>(`${config.public.apiBase}${path}`, {
method: 'DELETE',
headers: getHeaders(),
});
}
return { get, post, del };
}
```
### 错误处理
```typescript
// 全局错误拦截 (Nuxt plugin)
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('vue:error', (error) => {
const code = error?.statusCode;
if (code === 401) {
const userStore = useUserStore();
userStore.logout();
navigateTo('/login');
}
});
});
```
## 播放器架构
### VodPlayer 组件
```typescript
// components/VodPlayer.vue
// 播放类型判断
function getPlayType(url: string, parseUrl?: string): 'hls' | 'iframe' {
if (parseUrl) return 'iframe';
if (url.includes('.m3u8')) return 'hls';
if (url.startsWith('http')) return 'iframe';
return 'hls';
}
```
### HLS 模式
```typescript
import ArtPlayer from 'artplayer';
import artplayerPluginHls from 'artplayer-plugin-hls';
import Hls from 'hls.js';
const art = new ArtPlayer({
container: '.artplayer-app',
url: m3u8Url,
plugins: [artplayerPluginHls({ hls: Hls })],
// 预留扩展位
// plugins: [hlsPlugin, danmukuPlugin, subtitlePlugin],
});
```
### iframe 模式
```html
<iframe
:src="iframeSrc"
allowfullscreen
class="w-full aspect-video"
sandbox="allow-scripts allow-same-origin allow-popups"
/>
```
### 播放状态管理
```typescript
// stores/player.ts
export const usePlayerStore = defineStore('player', () => {
const currentSourceIndex = ref(0);
const currentEpisodeIndex = ref(0);
const progress = ref(0);
const duration = ref(0);
function switchSource(index: number) {
currentSourceIndex.value = index;
currentEpisodeIndex.value = 0;
progress.value = 0;
}
function switchEpisode(index: number) {
currentEpisodeIndex.value = index;
progress.value = 0;
}
function onTimeUpdate(p: number, d: number) {
progress.value = p;
duration.value = d;
}
return {
currentSourceIndex, currentEpisodeIndex,
progress, duration,
switchSource, switchEpisode, onTimeUpdate,
};
});
```
### 播放历史上报
```typescript
// composables/usePlayer.ts
// 进度上报: 每30秒或暂停/退出时上报
const REPORT_INTERVAL = 30_000;
function startProgressReport(vodId: number, sourceId: number, episode: string, playUrl: string) {
const playerStore = usePlayerStore();
const { post } = useApi();
let timer: ReturnType<typeof setInterval>;
function report() {
post('/user/history', {
vod_id: vodId,
source_id: sourceId,
episode,
play_url: playUrl,
progress: Math.floor(playerStore.progress),
duration: Math.floor(playerStore.duration),
});
}
onMounted(() => {
timer = setInterval(report, REPORT_INTERVAL);
});
onUnmounted(() => {
clearInterval(timer);
report();
});
}
```
## 用户鉴权
### Token 管理
```typescript
// stores/user.ts
export const useUserStore = defineStore('user', () => {
const token = useCookie('binv_token', { maxAge: 60 * 60 * 24 * 7 });
const userInfo = ref<UserInfo | null>(null);
const isLoggedIn = computed(() => !!token.value);
async function login(username: string, password: string) {
const { post } = useApi();
const res = await post<{ token: string; expires_in: number }>('/user/auth/login', {
username, password,
});
token.value = res.token;
await fetchProfile();
}
async function fetchProfile() {
if (!token.value) return;
const { get } = useApi();
userInfo.value = await get<UserInfo>('/user/auth/profile');
}
function logout() {
token.value = null;
userInfo.value = null;
}
return { token, userInfo, isLoggedIn, login, fetchProfile, logout };
});
```
### 路由守卫
```typescript
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to) => {
const userStore = useUserStore();
if (!userStore.isLoggedIn) {
return navigateTo(`/login?redirect=${to.fullPath}`);
}
});
```
```typescript
// pages/favorite.vue
definePageMeta({
middleware: 'auth',
});
```
## Naive UI 集成
### 按需引入
```typescript
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['nuxtjs-naive-ui'],
naiveui: {
themeConfig: true,
},
});
```
### 暗色模式
```typescript
// Naive UI 主题由 Nuxt app 提供
// 通过 nuxtjs-naive-ui 模块自动处理 SSR 兼容
```
### 常用组件映射
| 场景 | Naive UI 组件 |
|---|---|
| 海报卡片 | NCard + NImage |
| 分类Tab | NTabs / NTabPane |
| 按钮组 | NButton / NButtonGroup |
| 选集按钮 | NTag / NButton |
| 分页 | NPagination |
| 搜索输入 | NInput |
| 弹窗提示 | NMessage / NDialog |
| 骨架屏 | NSkeleton |
| 下拉菜单 | NDropdown (用户菜单) |
## 部署
### Docker
```dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm i -g corepack && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/.output ./.output
ENV HOST=0.0.0.0 PORT=3000
EXPOSE 3000
CMD ["node", ".output/server/index.mjs"]
```
### docker-compose.yml
```yaml
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000"
environment:
- NUXT_PUBLIC_API_BASE=http://api:9999
- NUXT_API_BASE_URL=http://api:9999
depends_on:
- api
restart: unless-stopped
api:
build: ../api
ports:
- "9999:9999"
restart: unless-stopped
```
### Nginx 反代(可选)
```nginx
server {
listen 80;
server_name binv.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
```
### 环境变量
```bash
# .env
NUXT_PUBLIC_API_BASE=/api # 前端请求前缀
NUXT_API_BASE_URL=http://api:9999 # Server proxy 目标
```
## 性能优化策略
| 策略 | 实现 | 说明 |
|---|---|---|
| SSR 首屏 | Nuxt 默认 | 首页/详情/分类 SSR |
| ISR 缓存 | `routeRules` 配置 | 热门页缓存 60s |
| 图片懒加载 | NImage + nuxt/image | 懒加载 + WebP |
| 骨架屏 | NSkeleton | 列表加载态 |
| 播放器懒加载 | defineAsyncComponent | 进入详情页才加载 |
| 路由预取 | NuxtLink prefetch | 默认开启 |
| Bundle 优化 | Naive UI tree-shake | 按需引入 |
| Gzip/Brotli | Nginx/Node | 传输压缩 |
### ISR 配置
```typescript
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
'/': { isr: 60 },
'/category/**': { isr: 60 },
'/vod/**': { isr: 300 },
'/search': { swr: false },
},
});
```