Vue前后端技能生成实战:从零搭建企业级应用架构

4次阅读
没有评论

共计 3976 个字符,预计需要花费 10 分钟才能阅读完成。

image.webp

痛点分析

刚接触 Vue 前后端分离开发的新手,往往会遇到以下典型问题:

Vue 前后端技能生成实战:从零搭建企业级应用架构

  • 跨域处理 :本地开发时前端端口与后端 API 端口不同,浏览器安全策略导致请求被拦截
  • 鉴权流程 :不清楚 JWT token 如何存储、刷新,以及如何与路由守卫配合
  • 状态管理混乱 :组件间共享数据时滥用 props 或事件总线,导致难以维护
  • API 调用不规范 :每个页面重复编写 axios 请求,缺乏统一错误处理
  • 部署配置错误 :生产环境出现 404 路由或静态资源加载失败

技术栈选型

前端工具对比

@startuml
left to right direction
skinparam monochrome true

frame "Vue CLI" {
  component "Webpack"
  component "Babel"
  component "ESLint"
}

frame "Vite" {
  component "ESBuild"
  component "Rollup"
  component "原生 ESM"
}

note "Vue CLI 更适合需要成熟生态的项目 \nVite 更适合追求极速启动的现代项目" as N1
@enduml

实际选择建议:

  • 企业级项目建议仍使用 Vue CLI(当前版本 5.x),因其插件系统更稳定
  • 创建命令对比:
    # Vue CLI
    npm install -g @vue/cli
    vue create my-project
    
    # Vite
    npm create vite@latest my-project --template vue-ts

后端框架选择

选用 Koa2 而非 Express 的核心原因:

  • 更轻量(600 行代码 vs 1800 行)
  • 支持 async/await 中间件
  • 更好的 TS 类型支持

初始化命令:

mkdir backend && cd backend
npm init -y
npm install koa @koa/router koa-bodyparser
npm install --save-dev typescript @types/node

核心实现

动态路由配置

// src/router/index.ts
import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router'

declare module 'vue-router' {
  interface RouteMeta {
    requiresAuth: boolean
    title?: string
  }
}

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    meta: {requiresAuth: false}
  },
  {
    path: '/dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: {requiresAuth: true}
  }
]

const router = createRouter({history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫示例
router.beforeEach((to, from) => {const token = localStorage.getItem('token')
  if (to.meta.requiresAuth && !token) {return '/login'}
})

export default router

模块化 Vuex

// src/store/modules/user.ts
interface UserState {
  token: string | null
  profile: {
    name: string
    avatar: string
  } | null
}

export const userModule = {
  namespaced: true,
  state: (): UserState => ({
    token: null,
    profile: null
  }),
  mutations: {SET_TOKEN(state: UserState, payload: string) {state.token = payload}
  },
  actions: {async login({ commit}, credentials) {const res = await api.login(credentials)
      commit('SET_TOKEN', res.data.token)
    }
  }
}

// src/store/index.ts
import {createStore} from 'vuex'
import {userModule} from './modules/user'

export default createStore({
  modules: {user: userModule}
})

Axios 拦截器封装

// src/utils/request.ts
import axios, {AxiosRequestConfig, AxiosResponse} from 'axios'

const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 10000
})

// 请求拦截
service.interceptors.request.use((config: AxiosRequestConfig) => {const token = localStorage.getItem('token')
  if (token) {config.headers!['Authorization'] = `Bearer ${token}`
  }
  return config
})

// 响应拦截
service.interceptors.response.use((response: AxiosResponse) => {return response.data},
  (error) => {if (error.response.status === 401) {router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service

避坑指南

开发环境 CORS

后端必须配置:

// backend/app.js
const cors = require('@koa/cors')

app.use(cors({
  origin: process.env.NODE_ENV === 'development' 
    ? 'http://localhost:8080' 
    : 'https://yourdomain.com',
  credentials: true
}))

生产环境缓存

Nginx 配置示例:

location / {
  try_files $uri $uri/ /index.html;
  expires 30d;
  add_header Cache-Control "public";
}

location /assets {
  expires 1y;
  access_log off;
  add_header Cache-Control "public";
}

性能优化

路由懒加载优化

修改 vue.config.js:

module.exports = {
  chainWebpack: config => {
    config.optimization.splitChunks({
      chunks: 'all',
      maxSize: 244 * 1024 // 244KB
    })
  }
}

接口节流

// src/utils/throttle.ts
export function throttle<T extends (...args: any[]) => any>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void {
  let lastCall = 0
  return (...args: Parameters<T>) => {const now = Date.now()
    if (now - lastCall >= delay) {
      lastCall = now
      return fn(...args)
    }
  }
}

// 使用示例
const search = throttle((keyword: string) => {api.search({ keyword})
}, 500)

代码规范

ESLint 配置

.eslintrc.js 关键配置:

module.exports = {
  extends: [
    'plugin:vue/vue3-recommended',
    'eslint:recommended',
    '@vue/typescript/recommended'
  ],
  rules: {
    'vue/multi-word-component-names': 'off',
    '@typescript-eslint/no-explicit-any': 'off'
  }
}

Git 提交规范

推荐使用 commitizen:

npm install -g commitizen
commitizen init cz-conventional-changelog --save-dev --save-exact

然后在 package.json 中添加:

{
  "scripts": {"commit": "cz"}
}

项目源码

完整可运行项目已上传 GitHub:
https://github.com/example/vue-koa-starter

git clone https://github.com/example/vue-koa-starter.git
cd vue-koa-starter
npm install
npm run dev

总结

通过这套架构实践,我们实现了:
1. 前后端完全分离的开发模式
2. 完善的类型安全体系
3. 可扩展的状态管理方案
4. 企业级的错误处理流程
5. 自动化代码质量保障

建议在实际项目中根据团队规模适当调整技术方案,核心是保持架构的一致性和可维护性。后续可以进一步集成 Docker 容器化部署和 CI/CD 流程。

正文完
 0
评论(没有评论)