shop-web/doc/系统架构文档.md

13 KiB

系统架构文档

架构概述

MobVue 是一个基于 Vue3 的移动端 H5 应用,采用现代化的前端技术栈,具备清晰的模块化设计和可扩展的架构。

技术架构

前端技术栈

┌─────────────────────────────────────────────────────────────┐
│                        MobVue 应用                          │
├─────────────────────────────────────────────────────────────┤
│  Vue 3 + Composition API + TypeScript + Vant UI             │
├─────────────────────────────────────────────────────────────┤
│  Pinia (状态管理) │ Vue Router (路由) │ UnoCSS (样式)       │
├─────────────────────────────────────────────────────────────┤
│  Vite (构建工具) │ Axios (HTTP客户端) │ ESLint (代码规范)   │
└─────────────────────────────────────────────────────────────┘

核心依赖关系

App.vue
    ├── Layout (布局系统)
    │   ├── NavBar (导航栏)
    │   ├── Tabbar (标签栏)
    │   └── RouterView (页面渲染)
    ├── Pinia Stores (状态管理)
    │   ├── User Store (用户状态)
    │   ├── Wx Store (微信状态)
    │   ├── Product Store (商品状态)
    │   └── Cart Store (购物车状态)
    └── Router (路由系统)
        ├── Route Guards (路由守卫)
        └── Route Configuration (路由配置)

模块架构

1. 核心模块

应用入口 (src/main.ts)

// 应用初始化流程
1. 创建 Vue 应用实例
2. 安装插件系统
3. 配置状态管理 (Pinia)
4. 配置路由系统 (Vue Router)
5. 挂载应用到 DOM

应用根组件 (src/App.vue)

// 主要职责
1. 全局配置提供器 (ConfigProvider)
2. 主题模式管理 (暗黑/亮色)
3. 微信回调处理
4. 用户认证状态管理
5. 布局系统容器

2. 布局系统 (src/layout/)

布局组件结构

Layout (主布局)
├── NavBar (导航栏)
│   ├── 标题显示
│   ├── 返回按钮
│   └── 操作按钮
├── Tabbar (标签栏)
│   ├── 首页
│   ├── 商品列表
│   ├── 审批中心
│   └── 个人中心
└── RouterView (页面内容)

布局配置

interface LayoutConfig {
  navBar: {
    showNavBar: boolean;      // 是否显示导航栏
    showLeftArrow: boolean;   // 是否显示返回箭头
    title?: string;           // 导航栏标题
  };
  tabbar: {
    showTabbar: boolean;      // 是否显示标签栏
    icon?: string;            // 标签图标
  };
}

3. 状态管理架构 (src/pinia/)

Store 设计模式

// Store 通用结构
export const useXxxStore = defineStore("xxx", () => {
  // 1. State (状态)
  const state = ref<StateType>(initialValue);

  // 2. Getters (计算属性)
  const computedState = computed(() => {
    return state.value.filter(...);
  });

  // 3. Actions (操作)
  const fetchData = async () => {
    // 异步操作
  };

  // 4. 返回暴露的属性和方法
  return { state, computedState, fetchData };
});

Store 依赖关系

User Store
    ├── 用户认证状态
    ├── 用户权限信息
    └── 用户基本信息

Wx Store
    ├── 微信认证状态
    ├── 用户 OpenID
    ├── 企业微信信息
    └── 余额信息

Product Store
    ├── 商品列表
    ├── 商品详情
    └── 商品分类

Cart Store
    ├── 购物车商品
    ├── 选中状态
    └── 结算信息

Order Store
    ├── 订单列表
    ├── 订单详情
    └── 订单状态

4. 路由架构 (src/router/)

路由分层设计

// 系统路由 (错误页面等)
export const systemRoutes: RouteRecordRaw[] = [
  { path: "/403", component: Error403 },
  { path: "/404", component: Error404 }
];

// 业务路由 (主要功能页面)
export const routes: RouteRecordRaw[] = [
  { path: "/", component: ProductList },
  { path: "/me", component: UserCenter },
  { path: "/order/:id", component: OrderDetail }
];

路由守卫流程

// 路由导航守卫流程
1. 检查白名单 (无需认证的页面)
2. 验证用户认证状态
3. 检查页面访问权限
4. 设置页面标题
5. 处理布局配置
6. 执行路由跳转

5. API 架构 (src/common/apis/)

API 模块化组织

apis/
├── users/          # 用户相关接口
│   ├── index.ts   # 接口方法
│   └── type.ts    # 类型定义
├── shop/           # 店铺相关接口
├── cabinet/        # 柜机相关接口
├── approval/       # 审批相关接口
└── ab98/           # AB98系统接口

HTTP 客户端架构

// Axios 配置层次
1. 创建实例配置
2. 请求拦截器 (添加 Token )
3. 响应拦截器 (统一错误处理)
4. 业务状态码处理
5. 全局错误处理

6. 工具函数架构 (src/common/utils/)

工具模块分类

utils/
├── cache/          # 缓存工具
│   ├── cookies.ts  # Cookie 操作
│   └── local-storage.ts # 本地存储
├── permission.ts   # 权限工具
├── wx.ts           # 微信工具
├── validate.ts     # 验证工具
└── datetime.ts     # 日期时间工具

7. 组合式函数架构 (src/common/composables/)

可复用逻辑

// 组合式函数设计模式
export function useXxx() {
  // 1. 响应式状态
  const state = ref(initialValue);

  // 2. 操作方法
  const action = () => {
    // 业务逻辑
  };

  // 3. 生命周期
  onMounted(() => {
    // 初始化逻辑
  });

  // 4. 返回暴露的 API
  return { state, action };
}

数据流架构

1. 组件间通信

Props/Emits (父子组件)

<!-- 父组件 -->
<ChildComponent
  :title="parentTitle"
  @update:title="handleTitleUpdate"
/>

<!-- 子组件 -->
<script setup lang="ts">
const props = defineProps<{ title: string }>();
const emit = defineEmits<{ 'update:title': [value: string] }>();
</script>

Provide/Inject (跨层级组件)

// 祖先组件
const theme = ref('light');
provide('theme', theme);

// 后代组件
const theme = inject<Ref<string>>('theme');

Pinia Store (全局状态)

// 在任何组件中使用
const userStore = useUserStore();
const { token, username } = storeToRefs(userStore);

2. API 数据流

数据获取流程

// 1. 组件触发 Action
const productStore = useProductStore();

// 2. Store 调用 API
const fetchProducts = async () => {
  loading.value = true;
  try {
    const response = await getProductListApi();
    if (response.code === 0) {
      products.value = response.data.products;
    }
  } finally {
    loading.value = false;
  }
};

// 3. 组件监听状态变化
watchEffect(() => {
  if (productStore.products.length > 0) {
    // 更新 UI
  }
});

3. 用户交互流程

典型用户操作流程

用户打开应用
    ↓
微信认证处理
    ↓
获取用户信息
    ↓
显示商品列表
    ↓
用户选择商品
    ↓
加入购物车
    ↓
创建订单
    ↓
支付结算
    ↓
订单完成

安全架构

1. 认证机制

微信 OAuth2.0 认证流程

// 微信认证流程
1. 重定向到微信授权页面
2. 用户授权后返回 code
3. 使用 code 换取 access_token
4. 获取用户 OpenID
5. 验证用户权限
6. 生成应用内 Token

Token 管理

// Token 存储策略
1. HTTP Only Cookie 存储
2. 自动续期机制
3. 安全退出清理
4. 跨域请求携带

2. 权限控制

路由级权限

// 路由守卫权限检查
const hasPermission = (route: RouteLocationNormalized) => {
  if (route.meta?.requiresAuth && !isAuthenticated) {
    return false;
  }
  if (route.meta?.roles && !hasRole(route.meta.roles)) {
    return false;
  }
  return true;
};

组件级权限

<!-- 权限指令使用 -->
<button v-permission="['admin']">管理员操作</button>

3. 数据安全

敏感信息保护

// 本地存储加密
const encryptData = (data: string) => {
  return btoa(encodeURIComponent(data));
};

const decryptData = (encrypted: string) => {
  return decodeURIComponent(atob(encrypted));
};

性能架构

1. 代码分割

路由级懒加载

// 动态导入组件
const ProductList = () => import('@/pages/product/ProductList.vue');

第三方库分割

// Vite 配置手动分块
manualChunks: {
  vue: ['vue', 'vue-router', 'pinia']
}

2. 缓存策略

组件缓存

<!-- KeepAlive 缓存 -->
<router-view v-slot="{ Component }">
  <keep-alive :include="cachedRoutes">
    <component :is="Component" />
  </keep-alive>
</router-view>

API 响应缓存

// 接口数据缓存
const cache = new Map();

const getCachedData = async (key: string, fetcher: () => Promise<any>) => {
  if (cache.has(key)) {
    return cache.get(key);
  }
  const data = await fetcher();
  cache.set(key, data);
  return data;
};

3. 资源优化

图片优化

<!-- 图片懒加载 -->
<img
  :src="product.image"
  loading="lazy"
  :alt="product.name"
/>

CSS 优化

/* UnoCSS 原子化类名 */
.un-p-4 { padding: 1rem; }
.un-bg-white { background-color: white; }
.un-rounded-lg { border-radius: 0.5rem; }

扩展性设计

1. 插件系统

插件注册机制

// 插件安装函数
export const installPlugins = (app: App) => {
  // 注册全局组件
  app.component('CustomComponent', CustomComponent);

  // 注册自定义指令
  app.directive('permission', permissionDirective);

  // 注册全局属性
  app.config.globalProperties.$utils = utils;
};

2. 配置系统

环境配置

// 多环境配置支持
const config = {
  development: {
    baseURL: 'http://localhost:3000',
    debug: true
  },
  production: {
    baseURL: 'https://api.example.com',
    debug: false
  }
};

3. 主题系统

动态主题切换

// 主题管理
const useTheme = () => {
  const isDark = ref(false);

  const toggleTheme = () => {
    isDark.value = !isDark.value;
    document.documentElement.classList.toggle('dark', isDark.value);
  };

  return { isDark, toggleTheme };
};

监控和调试

1. 开发工具

Vue DevTools 集成

// 开发环境启用
if (import.meta.env.DEV) {
  // 启用 Vue DevTools
}

控制台调试

// VConsole 移动端调试
import VConsole from 'vconsole';

if (import.meta.env.DEV) {
  new VConsole();
}

2. 错误监控

全局错误处理

// Vue 错误处理
app.config.errorHandler = (err, instance, info) => {
  console.error('Vue 错误:', err, info);
  // 发送错误报告
};

// 未处理 Promise 拒绝
window.addEventListener('unhandledrejection', (event) => {
  console.error('未处理的 Promise 拒绝:', event.reason);
});

部署架构

1. 构建优化

生产环境构建

// Vite 生产配置
build: {
  rollupOptions: {
    output: {
      manualChunks: {
        vue: ['vue', 'vue-router', 'pinia']
      }
    }
  },
  reportCompressedSize: false,
  chunkSizeWarningLimit: 2048
}

2. CDN 部署

静态资源优化

// 静态资源 CDN 配置
base: process.env.NODE_ENV === 'production'
  ? 'https://cdn.example.com/mobvue/'
  : '/'

总结

MobVue 采用现代化的前端架构设计,具备以下特点:

  1. 模块化设计: 清晰的模块边界和职责分离
  2. 类型安全: 全面的 TypeScript 支持
  3. 状态管理: 集中式的状态管理方案
  4. 性能优化: 多层次的性能优化策略
  5. 安全可靠: 完善的安全机制和错误处理
  6. 可扩展性: 灵活的插件和配置系统
  7. 开发体验: 优秀的开发工具和调试支持

这种架构设计确保了项目的可维护性、可扩展性和高性能,为移动端 H5 应用开发提供了坚实的基础。