Nuxt.js全栈高手养成指南:从零到高并发实战,手把手买通SSR+国内生态摆设+大厂级架构

[复制链接]
发表于 2025-9-22 23:37:34 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
阶段一:基础认知与快速上手

1:什么是Nuxt.js?为什么你必要它?

1.1 Nuxt.js 的定位

Nuxt.js 是一个基于 Vue.js 的 全栈开辟框架(留意:不是“库”),它的焦点目标是简化 Vue 应用的开辟流程,尤其擅长办理以下标题:


  • 服务端渲染 (SSR):让 Vue 应用拥有更好的 SEO 和首屏加载速率。
  • 静态站点天生 (SSG):将页面预渲染为静态 HTML,适合博客、文档站等。
  • 主动化设置:主动天生路由、代码拆分、优化构建设置,开辟者只需专注写代码。
1.2 与 Vue.js 的关系



  • Vue.js 是焦点:Nuxt.js 底层依赖 Vue.js,所有 Vue 的语法和特性(组件、相应式、指令等)在 Nuxt 中完全实用。
  • Nuxt.js 是扩展:它在 Vue 基础上添加了“约定大于设置”的目次结构、服务端渲染本领、模块化插件体系等高级功能。
1.3 焦点特性

(1) 渲染模式自由切换

模式形貌实用场景SSR (Server-Side Rendering)服务器及时天生 HTML 发送给欣赏器必要 SEO 的动态网站(电商、消息站)SSG (Static Site Generation)构建时预天生静态 HTML内容固定的站点(博客、企业官网)SPA (Single Page Application)纯客户端渲染对 SEO 无要求的背景管理体系(2) 主动路由体系



  • 无需手动设置路由:只需在 pages/ 目次下创建 .vue 文件,Nuxt 会主动天生路由。
  • 示例:创建 pages/about.vue → 主动天生 /about 路由。
(3) 模块化开辟



  • 官方/社区模块:一键集成 Axios(HTTP 请求)、Pinia(状态管理)、Tailwind CSS 等工具。
  • 设置简单:在 nuxt.config.js 中声明模块即可。
1.4 何时选择 Nuxt.js?

场景保举方案必要 SEO 优化的内容型网站Nuxt.js (SSR/SSG)纯背景管理体系(无需 SEO)直接使用 Vue.js (SPA)需快速搭建企业官网Nuxt.js (SSG) + 内容管理体系(如 WordPress)
2:10分钟创建你的第一个Nuxt项目

2.1 环境准备

步骤 1:安装 Node.js



  • 访问 Node.js 官网 下载 LTS 版本(如 v18.x)。
  • 安装后验证是否乐成:
    1. node -v  # 应输出版本号(如 v18.16.0)
    2. npm -v   # 应输出版本号(如 9.5.1)
    复制代码
步骤 2:选择包管理工具(npm 或 yarn)



  • 假如喜欢更快的速率,可安装 Yarn:
    1. npm install -g yarn
    2. yarn -v  # 验证版本
    复制代码
2.2 创建 Nuxt 项目

步骤 1:使用脚手架

  1. npx create-nuxt-app my-first-nuxt-app
复制代码


  • 假如使用 Yarn:
    1. yarn create nuxt-app my-first-nuxt-app
    复制代码
步骤 2:回答交互式标题

以下是保举小白选择的设置(方向键选择,回车确认):
  1. ? Programming language: JavaScript
  2. ? Package manager: Npm 或 Yarn(根据上一步选择)
  3. ? UI framework: None (先不用 UI 库,避免复杂度)
  4. ? Nuxt.js modules: None (后续手动添加)
  5. ? Linting tools: None (先跳过代码检查)
  6. ? Testing framework: None
  7. ? Rendering mode: Universal (SSR / SSG)
  8. ? Deployment target: Server (SSR)
  9. ? Development tools: jsconfig.json (可选)
  10. ? Continuous integration: None
  11. ? Version control system: Git
复制代码
步骤 3:启动开辟服务器

  1. cd my-first-nuxt-app
  2. npm run dev
  3.   # 或 yarn dev
复制代码


  • 访问 http://localhost:3000,你会看到默认接待页!
步骤 4:体验热重载 (Hot Reload)



  • 打开 pages/index.vue,修改 <h1> 标签内的笔墨。
  • 生存文件,欣赏器会主动革新表现最新内容。

3:解剖Nuxt项目结构

3.1 关键目次与文件

  1. my-first-nuxt-app/
  2. ├── pages/          # 页面组件,自动生成路由
  3. ├── layouts/        # 布局组件(如页头、页脚)
  4. ├── assets/         # 静态资源(CSS/图片/字体)
  5. ├── components/     # 可复用的 Vue 组件
  6. ├── nuxt.config.js  # Nuxt 配置文件
  7. └── package.json    # 项目依赖和脚本
复制代码
3.2 焦点文件详解

(1) pages/index.vue

  1. <template>
  2.   <div>
  3.     <h1>Welcome to Nuxt!</h1>
  4.   </div>
  5. </template>
复制代码


  • 这是你的首页组件,对应路由 /。
(2) layouts/default.vue

  1. <template>
  2.   <div>
  3.     <NuxtPage />  <!-- 页面内容将插入此处 -->
  4.   </div>
  5. </template>
复制代码


  • 默认结构,所有页面默认使用此结构。
  • <NuxtPage /> 是页面内容的占位符。
(3) nuxt.config.js

  1. export default {
  2.   // 配置 Nuxt 的核心选项
  3.   modules: [],     // 添加模块
  4.   css: [],         // 全局 CSS 文件
  5.   buildModules: [],// 开发环境模块
  6. }
复制代码

阶段二:页面开辟与路由基础

1. 创建你的第一个页面

步骤 1:新建 about 页面


  • 在 pages/ 目次下创建 about.vue 文件:
    1. <template>
    2.   <div>
    3.     <h1>关于我们</h1>
    4.     <p>这里是关于页面的内容。</p>
    5.   </div>
    6. </template>
    复制代码
  • 生存文件后,访问 http://localhost:3000/about,页面主动见效!
步骤 2:明确主动路由规则

文件路径天生的路由地址pages/index.vue/pages/about.vue/aboutpages/blog/index.vue/blogpages/users/_id.vue/users/:id2. 使用组件实当代码复用

步骤 1:创建公共组件


  • 在 components/ 下新建 Header.vue:
    1. <template>
    2.   <header>
    3.     <nav>
    4.       <NuxtLink to="/">首页</NuxtLink>
    5.       <NuxtLink to="/about">关于</NuxtLink>
    6.     </nav>
    7.   </header>
    8. </template>
    9. <style scoped>
    10. nav { padding: 20px; background: #f0f0f0; }
    11. a { margin-right: 15px; }
    12. </style>
    复制代码
步骤 2:在页面中引入组件

修改 pages/index.vue:
  1. <template>
  2.   <div>
  3.     <Header /> <!-- 使用组件 -->
  4.     <h1>Welcome to Nuxt!</h1>
  5.   </div>
  6. </template>
  7. <script>
  8. import Header from '@/components/Header.vue' // 导入组件
  9. export default {
  10.   components: { Header } // 注册组件
  11. }
  12. </script>
复制代码
3. 动态路由实战

步骤 1:创建动态路由页面


  • 在 pages/ 下新建 users/_id.vue(留意下划线前缀):
    1. <template>
    2.   <div>
    3.     <h1>用户详情页</h1>
    4.     <p>用户ID:{{ $route.params.id }}</p>
    5.   </div>
    6. </template>
    复制代码
  • 访问 http://localhost:3000/users/123,页面表现用户ID:123。
步骤 2:使用 <NuxtLink> 跳转

在 Header.vue 中添加链接:
  1. <NuxtLink to="/users/456">用户456</NuxtLink>
复制代码
4. 结构体系精讲

步骤 1:自界说结构


  • 创建 layouts/custom.vue:
    1. <template>
    2.   <div>
    3.     <Header />
    4.     <main>
    5.       <slot /> <!-- 页面内容插入点 -->
    6.     </main>
    7.     <footer style="margin-top: 50px; text-align: center;">
    8.       <p>© 2023 我的网站</p>
    9.     </footer>
    10.   </div>
    11. </template>
    12. <script>
    13. import Header from '@/components/Header.vue'
    14. export default {
    15.   components: { Header }
    16. }
    17. </script>
    复制代码
步骤 2:指定页面使用结构

修改 pages/about.vue:
  1. <script>
  2. export default {
  3.   layout: 'custom' // 使用自定义布局
  4. }
  5. </script>
复制代码
5. 导航组件进阶

使用 <NuxtLink> 的激活类


  • 修改 Header.vue 样式:
    1. .nuxt-link-active {
    2.   font-weight: bold;
    3.   color: #42b983;
    4. }
    复制代码
  • 当前路由对应的链接会主动添加 nuxt-link-active 类。

本阶段练习任务


  • 创建一个 /contact 页面,展示接洽方式。
  • 实现动态路由 /posts/:slug,表现文章标题。
  • 为所有页面添加全局页脚(通过默认结构修改)。

阶段三:数据获取与状态管理

1. 数据获取的两种焦点方式

Nuxt.js 提供两种异步数据获取方法:asyncData(服务端获取)和 fetch(客户端或服务端获取)。
(1) asyncData:服务端数据预获取



  • 特性:在页面渲染前运行(服务端),SEO 友爱。
  • 实用场景:必要 SEO 的页面数据(如商品详情页)。
  • 示例:在 pages/posts/_id.vue 中:
    1. <template>
    2.   <div>
    3.     <h1>{{ post.title }}</h1>
    4.     <p>{{ post.content }}</p>
    5.   </div>
    6. </template>
    7. <script>
    8. export default {
    9.   async asyncData({ params }) {
    10.     // 模拟 API 请求
    11.     const post = await $fetch(`https://api.example.com/posts/${params.id}`)
    12.     return { post } // 返回的数据会合并到组件 data 中
    13.   }
    14. }
    15. </script>
    复制代码
(2) fetch:客户端或服务端获取



  • 特性:可以在客户端或服务端运行,适合非关键数据。
  • 示例:在 pages/index.vue 中:
    1. <script>
    2. export default {
    3.   data() {
    4.     return { products: [] }
    5.   },
    6.   async fetch() {
    7.     this.products = await $fetch('https://api.example.com/products')
    8.   }
    9. }
    10. </script>
    复制代码

2. 使用 Axios 发送 HTTP 请求

步骤 1:安装 Axios 模块

  1. npm install @nuxtjs/axios
复制代码
步骤 2:设置 nuxt.config.js

  1. export default {
  2.   modules: ['@nuxtjs/axios'],
  3.   axios: {
  4.     baseURL: 'https://api.example.com' // 基础 URL
  5.   }
  6. }
复制代码
步骤 3:在组件中使用

  1. <script>
  2. export default {
  3.   async asyncData({ $axios }) {
  4.     const users = await $axios.$get('/users')
  5.     return { users }
  6.   }
  7. }
  8. </script>
复制代码

3. 状态管理:Pinia 入门

Pinia 是 Vue 官方保举的状态管理库,替代 Vuex。
步骤 1:安装 Pinia

  1. npm install @pinia/nuxt
复制代码
步骤 2:设置 nuxt.config.js

  1. export default {
  2.   modules: ['@pinia/nuxt']
  3. }
复制代码
步骤 3:创建 Store


  • 新建 stores/counter.js:
    1. import { defineStore } from 'pinia'
    2. export const useCounterStore = defineStore('counter', {
    3.   state: () => ({ count: 0 }),
    4.   actions: {
    5.     increment() {
    6.       this.count++
    7.     }
    8.   }
    9. })
    复制代码
步骤 4:在组件中使用

  1. <template>
  2.   <div>
  3.     <button @click="counter.increment">点击次数:{{ counter.count }}</button>
  4.   </div>
  5. </template>
  6. <script>
  7. import { useCounterStore } from '~/stores/counter'
  8. export default {
  9.   setup() {
  10.     const counter = useCounterStore()
  11.     return { counter }
  12.   }
  13. }
  14. </script>
复制代码

4. 数据缓存与错误处理

(1) 使用 useAsyncData (Nuxt 3)

  1. <script setup>
  2. const { data, error } = await useAsyncData('posts', () => {
  3.   return $fetch('https://api.example.com/posts')
  4. })
  5. if (error.value) {
  6.   console.error('数据加载失败:', error.value)
  7. }
  8. </script>
复制代码
(2) 全局错误页面


  • 创建 layouts/error.vue:
    1. <template>
    2.   <div class="error-container">
    3.     <h1 v-if="error.statusCode === 404">页面不存在</h1>
    4.     <h1 v-else>发生错误:{{ error.message }}</h1>
    5.     <NuxtLink to="/">返回首页</NuxtLink>
    6.   </div>
    7. </template>
    8. <script>
    9. export default {
    10.   props: ['error']
    11. }
    12. </script>
    复制代码

本阶段练习任务


  • 创建一个 /news 页面,从公开 API(如 NewsAPI)获取消息列表并渲染。
  • 实现一个购物车功能:通过 Pinia 管理商品添加/删除状态。
  • 在动态路由页 /posts/:id 中添加加载状态提示和错误边界处理。

阶段四:摆设与性能优化(国内版)

1. 国内主流摆设方案

(1) 静态站点摆设(SSG)

实用场景:博客、企业官网、文档站等静态内容。
保举平台:


  • 阿里云 OSS(对象存储)
  • 腾讯云 COS(对象存储)
  • Gitee Pages(码云静态托管,适合开源项目)
  • 七牛云 Kodo
(2) 服务端渲染摆设(SSR)

实用场景:动态网站(电商、交际平台)。
保举平台:


  • 阿里云 ECS(云服务器)
  • 腾讯云 CVM(云服务器)
  • 华为云弹性云服务器
  • Serverless 服务(阿里云函数盘算、腾讯云 SCF)

2. 静态站点摆设实战(以阿里云 OSS 为例)

步骤 1:天生静态文件


  • 修改 nuxt.config.js:
    1. export default {
    2.   target: 'static' // 指定生成静态站点
    3. }
    复制代码
  • 构建并天生静态文件:
    1. npm run generate
    复制代码

    • 产物会天生在 dist/ 目次。

步骤 2:上传到阿里云 OSS


  • 创建 OSS Bucket:

    • 登录 阿里云控制台,创建 Bucket,选择「公共读」权限。
    • 地区选择离用户近的(如华东1-杭州)。

  • 上传文件:

    • 在 OSS 控制台进入 Bucket,点击「上传文件」,将 dist/ 目次下的所有内容上传。
    • 或使用下令行工具 ossutil:
      1. ossutil cp -r dist/ oss://你的Bucket名称/ --recursive
      复制代码

  • 绑定自界说域名(可选):

    • 在 Bucket 的「域名管理」中绑定已存案的域名,并设置 CDN 加速。


3. 服务端渲染摆设实战(以腾讯云 CVM 为例)

步骤 1:服务器准备


  • 购买腾讯云 CVM 实例(保举 CentOS 或 Ubuntu 体系)。
  • 通过 SSH 毗连服务器:
    1. ssh root@你的服务器IP
    复制代码
步骤 2:摆设 Node.js 环境


  • 安装 Node.js 和 npm:
    1. # Ubuntu/Debian
    2. curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
    3. sudo apt install -y nodejs
    4. # CentOS
    5. curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
    6. sudo yum install -y nodejs
    复制代码
步骤 3:摆设 Nuxt 项目


  • 将代码上传到服务器(使用 Git 或 SFTP 工具)。
  • 安装依赖并构建:
    1. npm install
    2. npm run build
    复制代码
  • 使用 PM2 守护进程:
    1. npm install pm2 -g
    2. pm2 start "npm run start" --name nuxt-app
    复制代码

4. 国内性能优化本领

(1) 图片优化



  • 使用腾讯云数据万象(CI):

    • 主动压缩、格式转换、缩略图天生。
    • 在 nuxt.config.js 中设置图片域名:
      1. export default {
      2.   image: {
      3.     domains: ['你的Bucket.ci.tencentcloudcs.com']
      4.   }
      5. }
      复制代码

  • 懒加载:
    1. <NuxtImg src="image.jpg" loading="lazy" />
    复制代码
(2) CDN 加速



  • 阿里云 CDN 或 腾讯云 CDN:

    • 将静态资源(JS/CSS/图片)托管到 CDN,提拔访问速率。
    • 在 nuxt.config.js 中设置资源路径:
      1. export default {
      2.   build: {
      3.     publicPath: 'https://你的CDN域名/_nuxt/'
      4.   }
      5. }
      复制代码

(3) 代码压缩与合并



  • 启用 Brotli 压缩(需服务器支持):
    1. // nuxt.config.js
    2. export default {
    3.   build: {
    4.     compress: {
    5.       brotli: true,
    6.       gzip: true
    7.     }
    8.   }
    9. }
    复制代码
(4) 缓存计谋



  • OSS/COS 设置缓存头:

    • 在对象存储控制台为静态文件设置 Cache-Control: max-age=31536000(1年)。

  • API 请求缓存:
    1. // 使用内存缓存
    2. const cachedData = useState('data', () => null)
    3. if (!cachedData.value) {
    4.   cachedData.value = await $fetch('/api/data')
    5. }
    复制代码

5. 国内监控监控与分析工具



  • 性能监测:

    • 阿里云 ARMS(应用及时监控监控)
    • 腾讯云前端性能监控监控(RUM)

  • SEO 分析:

    • 百度统计、友盟+

  • 错误追踪:

    • Sentry 国内版(https://sentry.cn)


本阶段练习任务


  • 将 Nuxt 项目摆设到 Gitee Pages(需关联码云堆栈并开启 Pages 服务)。
  • 使用 腾讯云数据万象 对首页图片举行压缩和 WebP 格式转换。
  • 通过 阿里云 CDN 加速静态资源,对比加速前后的加载速率。

阶段五:进阶实战与生态集成

1. 中心件(Middleware):路由守卫与权限控制

(1) 什么是中心件?



  • 界说:在页面渲染前实行的代码,用于全局或页面级的逻辑处理(如身份验证、日志日志记载)。
  • 运行环境:服务端(SSR)或客户端(SPA)。
(2) 实战:实现登录拦截


  • 创建中心件文件
    在根目次新建 middleware/auth.js:
    1. export default function ({ redirect, store }) {
    2.   // 假设 Pinia 存储用户状态
    3.   if (!store.auth.isLoggedIn) {
    4.     return redirect('/login') // 未登录跳转到登录页
    5.   }
    6. }
    复制代码
  • 应用中心件

    • 全局见效(在 nuxt.config.js 中设置):
      1. export default {
      2.   router: { middleware: ['auth'] }
      3. }
      复制代码
    • 页面级见效(在页面组件中):
      1. <script>
      2. export default {
      3.   middleware: 'auth' // 仅当前页面生效
      4. }
      5. </script>
      复制代码


2. 插件开辟:扩展 Nuxt 本领

(1) 封装 Axios 拦截器(适配国内常见鉴权)


  • 创建插件文件 plugins/axios.js:
    1. export default function ({ $axios, store }) {
    2.   $axios.onRequest(config => {
    3.     // 添加腾讯云鉴权头部(示例)
    4.     config.headers['X-Signature'] = store.auth.token
    5.     return config
    6.   })
    7.   $axios.onError(error => {
    8.     if (error.response.status === 401) {
    9.       // Token 过期跳转登录
    10.       window.location.href = '/login?expired=1'
    11.     }
    12.     return Promise.reject(error)
    13.   })
    14. }
    复制代码
  • 注册插件
    在 nuxt.config.js 中:
    1. export default {
    2.   plugins: ['@/plugins/axios']
    3. }
    复制代码
(2) 集成微信 JS-SDK


  • 安装依赖:
    1. npm install weixin-js-sdk
    复制代码
  • 创建插件 plugins/wx-sdk.js:
    1. import wx from 'weixin-js-sdk'
    2. export default ({ app }, inject) => {
    3.   inject('wx', wx) // 全局注入 this.$wx
    4. }
    复制代码

3. TypeScript 深度支持

(1) 启用 TypeScript


  • 安装依赖:
    1. npm install @nuxt/typescript-build @nuxt/types --save-dev
    复制代码
  • 设置 nuxt.config.js:
    1. export default {
    2.   buildModules: ['@nuxt/typescript-build']
    3. }
    复制代码
  • 创建范例声明文件 types/index.d.ts:
    1. import { User } from '~/types/user'
    2. declare module '@nuxt/types' {
    3.   interface Context {
    4.     $auth: User // 扩展上下文类型
    5.   }
    6. }
    复制代码
(2) 范例化 Pinia Store

修改 stores/counter.ts:
  1. import { defineStore } from 'pinia'
  2. interface CounterState {
  3.   count: number
  4. }
  5. export const useCounterStore = defineStore('counter', {
  6.   state: (): CounterState => ({ count: 0 }),
  7.   actions: {
  8.     increment() {
  9.       this.count++
  10.     }
  11.   }
  12. })
复制代码

4. 集成国内 UI 框架:Vant

(1) 安装与设置


  • 安装 Vant:
    1. npm install vant @vant/auto-import-resolver
    复制代码
  • 设置 nuxt.config.js:
    1. export default {
    2.   buildModules: [
    3.     ['@nuxtjs/vuetify', { autoImport: true }] // 自动按需引入
    4.   ],
    5.   css: ['vant/lib/index.css']
    6. }
    复制代码
(2) 在组件中使用

  1. <template>
  2.   <van-button type="primary" @click="submit">提交</van-button>
  3. </template>
  4. <script>
  5. // 无需手动导入,自动引入!
  6. export default {
  7.   methods: {
  8.     submit() { /* ... */ }
  9.   }
  10. }
  11. </script>
复制代码

5. 百度 SEO 优化实战

(1) 主动天生 sitemap


  • 安装模块:
    1. npm install @nuxtjs/sitemap
    复制代码
  • 设置 nuxt.config.js:
    1. export default {
    2.   modules: ['@nuxtjs/sitemap'],
    3.   sitemap: {
    4.     hostname: 'https://你的域名.com',
    5.     routes: async () => {
    6.       // 动态生成路由(如从 API 获取)
    7.       return ['/about', '/contact']
    8.     }
    9.   }
    10. }
    复制代码
(2) 百度主动推送

在 nuxt.config.js 中添加:
  1. export default {
  2.   head: {
  3.     script: [
  4.       {
  5.         src: 'https://zz.bdstatic.com/linksubmit/push.js', // 百度推送 JS
  6.         async: true
  7.       }
  8.     ]
  9.   }
  10. }
复制代码

本阶段练习任务


  • 开辟一个中心件:实现管理员权限控制(/admin 路由仅允许 admin 脚色访问)。
  • 封装插件:为 Axios 添加腾讯云 API 的公共参数签名逻辑。
  • TypeScript 改造:将已有 Vue 组件转换为 TypeScript,并界说接口范例。
  • Vant 实战:使用 Vant 组件构建移动端注册表单。

阶段六:全栈开辟与微服务架构

1. 全栈架构设计

(1) 技能选型

模块国内保举方案前端Nuxt.js (SSR) + Vant(移动端) / Element Plus(PC端)后端Nest.js(企业级) / Midway.js(阿里云生态) / Egg.js(阿里系)数据库MySQL(阿里云 RDS) / MongoDB(腾讯云 MongoDB)云服务阿里云 Serverless(函数盘算 + API 网关) / 腾讯云云开辟(TCB)摆设容器化(阿里云 ACK / 腾讯云 TKE) + CDN 加速
2. 实战:Nuxt.js + Midway.js 全栈开辟

(1) 后端服务搭建(Midway.js)


  • 初始化项目:
    1. npm init midway@latest -y
    复制代码
    选择 koa-v3 模板。
  • 创建商品查询接口:
    src/controller/product.controller.ts:
    1. import { Controller, Get, Inject } from '@midwayjs/core'
    2. import { Context } from '@midwayjs/koa'
    3. @Controller('/api/product')
    4. export class ProductController {
    5.   @Inject()
    6.   ctx: Context
    7.   @Get('/:id')
    8.   async getProduct(): Promise<any> {
    9.     const id = this.ctx.params.id
    10.     // 模拟数据库查询
    11.     return { code: 200, data: { id, name: `商品${id}`, price: 99.9 } }
    12.   }
    13. }
    复制代码
  • 当地运行:
    1. npm run dev
    复制代码
    访问 http://localhost:7001/api/product/123 测试接口。

(2) 前端 Nuxt.js 集成


  • 设置署理办理跨域:
    nuxt.config.js:
    1. export default {
    2.   modules: ['@nuxtjs/axios'],
    3.   axios: {
    4.     proxy: true // 开启代理
    5.   },
    6.   proxy: {
    7.     '/api/': {
    8.       target: 'http://localhost:7001',
    9.       pathRewrite: { '^/api/': '' }
    10.     }
    11.   }
    12. }
    复制代码
  • 页面调用接口:
    pages/product/_id.vue:
    1. <template>
    2.   <div>
    3.     <h1>{{ product.name }}</h1>
    4.     <p>价格:{{ product.price }}元</p>
    5.   </div>
    6. </template>
    7. <script>
    8. export default {
    9.   async asyncData({ $axios, params }) {
    10.     const { data } = await $axios.get(`/api/product/${params.id}`)
    11.     return { product: data }
    12.   }
    13. }
    14. </script>
    复制代码

3. 微服务架构实战(阿里云函数盘算)

(1) 将 Midway 后端摆设为 Serverless


  • 安装 Serverless 工具:
    1. npm install @midwayjs/serverless-scf -g
    复制代码
  • 设置 f.yml:
    1. service:
    2.   name: nuxt-demo-backend
    3. provider:
    4.   name: aliyun
    5.   region: cn-hangzhou
    6. functions:
    7.   product:
    8.     handler: product.default
    9.     events:
    10.       - http:
    11.           path: /api/product/{id}
    12.           method: get
    复制代码
  • 摆设到阿里云:
    1. midway deploy
    复制代码

(2) 前端对接云函数

修改 nuxt.config.js 署理设置:
  1. proxy: {
  2.   '/api/': {
  3.     target: 'https://你的云函数网关地址',
  4.     pathRewrite: { '^/api/': '' }
  5.   }
  6. }
复制代码

4. 微前端架构集成(qiankun)

(1) 主应用设置(Nuxt.js)


  • 安装 qiankun:
    1. npm install qiankun -S
    复制代码
  • 主应用入口插件 plugins/qiankun.js:
    1. import { registerMicroApps, start } from 'qiankun'
    2. export default ({ app }) => {
    3.   registerMicroApps([
    4.     {
    5.       name: 'vue-subapp',
    6.       entry: '//子应用域名/subapp/',
    7.       container: '#subapp-container',
    8.       activeRule: '/subapp'
    9.     }
    10.   ])
    11.   start()
    12. }
    复制代码
  • 在结构中添加容器:
    1. <template>
    2.   <div id="main-app">
    3.     <Header />
    4.     <div id="subapp-container"></div>
    5.   </div>
    6. </template>
    复制代码

(2) 子应用(Vue.js)适配


  • 导出生命周期钩子:
    subapp/src/public-path.js:
    1. if (window.__POWERED_BY_QIANKUN__) {
    2.   __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
    3. }
    复制代码
  • 修改入口文件:
    1. import './public-path'
    2. import Vue from 'vue'
    3. import App from './App.vue'
    4. let instance = null
    5. function render(props = {}) {
    6.   const { container } = props
    7.   instance = new Vue({
    8.     render: h => h(App)
    9.   }).$mount(container ? container.querySelector('#app') : '#app')
    10. }
    11. // 独立运行时
    12. if (!window.__POWERED_BY_QIANKUN__) {
    13.   render()
    14. }
    15. export async function bootstrap() {}
    16. export async function mount(props) { render(props) }
    17. export async function unmount() { instance.$destroy() }
    复制代码

5. 连续集成与摆设(CI/CD)

(1) 使用 GitLab CI 主动化摆设


  • 编写 .gitlab-ci.yml:
    1. stages:  - build  - deploycache:  paths:    - node_modules/build_frontend:  stage: build  image: node:16  script:    - npm install    - npm run generate
    2.   artifacts:    paths:      - dist/deploy_oss:  stage: deploy  image: alpine  script:    - apk add --no-cache python3 py3-pip    - pip install oss2    - python3 deploy_oss.py  # 自界说上传脚本
    复制代码
  • 阿里云 OSS 上传脚本 deploy_oss.py:
    1. import oss2
    2. auth = oss2.Auth('你的AK', '你的SK')
    3. bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'bucket名称')
    4. for root, dirs, files in os.walk('dist'):
    5.     for file in files:
    6.         local_path = os.path.join(root, file)
    7.         remote_path = local_path.replace('dist/', '')
    8.         bucket.put_object_from_file(remote_path, local_path)
    复制代码

本阶段练习任务


  • 全栈实战:基于 Nuxt + Midway 实现一个商品管理体系(增编削查)。
  • 微服务拆分:将用户模块拆分为独立云函数并集成。
  • 微前端改造:将背景管理模块作为子应用接入 qiankun 主应用。
  • CI/CD 实战:设置 GitLab CI 实现主动摆设到阿里云 OSS。

阶段七:性能调优与安全加固

一、性能调优进阶

1. 服务端性能优化

国内场景痛点:高并发访问、南北网络延迟差别
办理方案:


  • (1) 服务端渲染缓存(SSR Cache)
    1. // nuxt.config.js
    2. export default {
    3.   render: {
    4.     http2: { push: true }, // 开启 HTTP/2 推送
    5.     static: { maxAge: 1000 * 60 * 60 * 24 }, // 静态资源缓存
    6.     cdn: {
    7.       use: true, // 启用 CDN
    8.       domain: 'https://你的阿里云CDN域名'
    9.     }
    10.   }
    11. }
    复制代码
  • (2) 使用 Redis 缓存热门数据
    1. // 阿里云 Redis 连接示例(需安装 ioredis)
    2. import Redis from 'ioredis'
    3. const redis = new Redis({
    4.   host: '阿里云Redis实例地址',
    5.   port: 6379,
    6.   password: '你的密码'
    7. })
    8. // Nuxt 插件中缓存接口数据
    9. export default async ({ $axios }, inject) => {
    10.   inject('cacheGet', async (key, url) => {
    11.     const cached = await redis.get(key)
    12.     if (cached) return JSON.parse(cached)
    13.     const data = await $axios.$get(url)
    14.     await redis.setex(key, 3600, JSON.stringify(data)) // 缓存1小时
    15.     return data
    16.   })
    17. }
    复制代码
2. 客户端性能优化

国内场景痛点:弱网环境、低端安卓装备兼容性
办理方案:


  • (1) 首屏关键 CSS 内联
    1. // nuxt.config.js
    2. export default {
    3.   build: {
    4.     extractCSS: {
    5.       ignoreOrder: true,
    6.       inline: ['app.css'] // 内联关键 CSS
    7.     }
    8.   }
    9. }
    复制代码
  • (2) 按需加载第三方库(如高德舆图)
    1. // plugins/amap.js
    2. export default ({ app }, inject) => {
    3.   inject('loadAMap', () => {
    4.     return new Promise((resolve) => {
    5.       if (window.AMap) return resolve(window.AMap)
    6.       const script = document.createElement('script')
    7.       script.src = 'https://webapi.amap.com/maps?v=2.0&key=你的高德地图Key'
    8.       script.onload = () => resolve(window.AMap)
    9.       document.head.appendChild(script)
    10.     })
    11.   })
    12. }
    复制代码
3. 数据库优化

国内云服务集成:


  • 阿里云 PolarDB(兼容 MySQL,主动弹性扩展)
  • 腾讯云 TDSQL-C(Serverless 数据库)
    优化本领:
  1. -- 示例:添加索引提升查询速度
  2. ALTER TABLE products
  3. ADD INDEX idx_category_status (category_id, status);
复制代码

二、安全加固实战

1. 基础安全防护

(1) HTTPS 逼迫跳转


  • 国内免费 SSL 证书:

    • 阿里云 SSL 证书(免费 DV 版)
    • 腾讯云 TrustAsia 免费证书

  • Nginx 设置:
    1. server {
    2.   listen 80;
    3.   server_name yourdomain.com;
    4.   return 301 https://$server_name$request_uri;
    5. }
    复制代码
(2) 防止 XSS 攻击


  • CSP 内容安全计谋:
    1. // nuxt.config.js
    2. export default {
    3.   head: {
    4.     meta: [
    5.       {
    6.         'http-equiv': 'Content-Security-Policy',
    7.         content: `default-src 'self' https://*.aliyuncs.com; script-src 'self' 'unsafe-inline' https://unpkg.com`
    8.       }
    9.     ]
    10.   }
    11. }
    复制代码
2. 接口安全防护

(1) CSRF Token 校验
  1. // 使用 @nuxtjs/axios 模块配置
  2. export default {
  3.   axios: {
  4.     credentials: true,
  5.     baseURL: process.env.API_BASE_URL,
  6.     proxyHeaders: false,
  7.     retry: { retries: 3 }
  8.   },
  9.   modules: ['@nuxtjs/axios'],
  10.   // 生成 CSRF Token
  11.   serverMiddleware: [
  12.     { path: '/api/csrf', handler: '~/server-middleware/csrf.js' }
  13.   ]
  14. }
复制代码
(2) 敏感数据脱敏
  1. // 使用中间件过滤敏感字段
  2. export default function ({ res }) {
  3.   res.setHeader('X-Content-Type-Options', 'nosniff')
  4.   res.setHeader('X-XSS-Protection', '1; mode=block')
  5. }
复制代码
3. 防爬虫与 CC 攻击

国内工具保举:


  • 阿里云 WAF(Web 应用防火墙)
  • 腾讯云天御防爬服务
    设置示例:
  1. // 在 Nuxt 中识别爬虫并拦截
  2. export default function (req, res, next) {
  3.   const userAgent = req.headers['user-agent']
  4.   const isBot = /bot|spider|crawl|scraping/i.test(userAgent)
  5.   if (isBot) {
  6.     res.statusCode = 403
  7.     return res.end('Forbidden')
  8.   }
  9.   next()
  10. }
复制代码

三、合规与监控

1. 等保 2.0 合规要求



  • 日志日志留存:使用阿里云日志日志服务(SLS)存储 6 个月以上
  • 审计追踪:接入阿里云 ActionTrail
  • 数据加密:启用阿里云 KMS 密钥管理
2. 及时监控方案

国内保举组合:


  • 前端监控:阿里云前端监控(FMP)
  • 错误追踪:Sentry 国内版(sentry.io)
  • API 监控:腾讯云 APM
设置示例(阿里云 FMP):
  1. // nuxt.config.js
  2. export default {
  3.   head: {
  4.     script: [
  5.       {
  6.         src: 'https://g.alicdn.com/sd/sentry/loader/your-sdk.js',
  7.         async: true,
  8.         onload: `Sentry.init({ dsn: '你的DSN' })`
  9.       }
  10.     ]
  11.   }
  12. }
复制代码

四、实战练习


  • 性能调优:

    • 将 SSR 页面接入阿里云 CDN,对比首屏加载时间
    • 使用 Chrome Performance 工具分析并优化一个低性能页面

  • 安全加固:

    • 申请免费 SSL 证书并设置 HTTPS 逼迫跳转
    • 为敏感接口添加 CSRF Token 校验

  • 合规改造:

    • 设置阿里云 WAF 防御 SQL 注入攻击
    • 接入 Sentry 国内版实现错误监控



阶段八:大厂级项目实战复盘——电商平台全栈开辟

一、项目配景与需求

1. 业务场景



  • 目标:开辟一个符合国内电商业务特点的全栈应用,支持高并发、高可用、安全合规。
  • 焦点功能:

    • 商品展示(SSR 渲染 + CDN 加速)
    • 用户体系(手机号登录 + 微信授权)
    • 订单管理(状态机设计)
    • 付出体系(微信付出 + 付出宝)
    • 及时关照(WebSocket + 短信推送)

2. 技能选型

模块国内技能栈前端Nuxt.js (SSR) + Vant UI + 高德舆图(物流追踪)后端Midway.js (阿里系) + MySQL(阿里云 RDS) + Redis(阿里云 KVStore)付出微信付出(JSAPI) + 付出宝(手机网站付出)摆设阿里云 ACK(容器服务) + SLB(负载均衡) + 日志服务(SLS)监控阿里云 ARMS(应用监控) + 云盾(安全防护)
二、项目架构设计

1. 架构图

  1. 用户浏览器 → 阿里云 CDN(缓存静态资源) → 阿里云 SLB → Nuxt 服务集群(SSR)
  2.                           ↓
  3.                    Midway 微服务集群(订单/支付/商品)
  4.                           ↓
  5.                   阿里云 RDS(MySQL) + Redis(缓存/分布式锁)
复制代码
2. 微服务拆分

服务名称功能形貌技能实现商品服务商品详情、搜索、分类Midway.js + MySQL订单服务下单、付出状态回调、超时关闭Midway.js + Redis 分布式锁用户服务登录、权限管理、地址簿Midway.js + JWT付出服务聚合微信/付出宝付出、对账Midway.js + 微信付出 SDK
三、实战开辟步骤

1. 商品模块开辟(SSR 极致优化)

(1) 商品详情页 SSR 缓存
  1. // nuxt.config.js
  2. export default {
  3.   render: {
  4.     ssrCache: {
  5.       max: 1000, // 缓存 1000 个页面
  6.       ttl: 60 * 1000 // 缓存 1 分钟
  7.     }
  8.   }
  9. }
复制代码
(2) 图片懒加载 + WebP 主动转换
  1. <template>
  2.   <NuxtImg
  3.     src="/product.jpg"
  4.     :modifiers="{ format: 'webp' }"
  5.     loading="lazy"
  6.     provider="aliyun"
  7.   />
  8. </template>
复制代码
2. 用户认证(国内手机号+微信)

(1) 短信登录(阿里云 SMS)
  1. // Midway 控制器
  2. @Post('/sms/login')
  3. async smsLogin(@Body() { phone, code }) {
  4.   const cacheCode = await redis.get(`sms:${phone}`)
  5.   if (code !== cacheCode) throw new Error('验证码错误')
  6.   const user = await userService.findOrCreate(phone)
  7.   return { token: generateJWT(user.id) }
  8. }
复制代码
(2) 微信授权登录
  1. // Nuxt 插件
  2. export default ({ app }, inject) => {
  3.   inject('wechatLogin', () => {
  4.     const redirectUri = encodeURIComponent('https://你的域名/auth/wechat')
  5.     window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo`
  6.   })
  7. }
复制代码
3. 订单付出(微信+付出宝聚合)

(1) 微信付出同一下单
  1. // Midway 支付服务
  2. async createWechatPay(order) {
  3.   const result = await wxpay.unifiedOrder({
  4.     body: order.title,
  5.     out_trade_no: order.no,
  6.     total_fee: order.amount * 100,
  7.     openid: order.user.openid
  8.   })
  9.   return {
  10.     paymentUrl: result.mweb_url,
  11.     paySign: result.sign
  12.   }
  13. }
复制代码
(2) 付出效果回调校验
  1. @Post('/pay/notify/wechat')
  2. async wechatNotify(@Body() xmlData) {
  3.   const result = await wxpay.verifySign(xmlData)
  4.   if (result.return_code === 'SUCCESS') {
  5.     await orderService.completePayment(result.out_trade_no)
  6.   }
  7.   return '<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>'
  8. }
复制代码

四、摆设与运维

1. 容器化摆设(阿里云 ACK)

(1) Dockerfile 设置
  1. FROM node:16-alpine
  2. WORKDIR /app
  3. COPY . .
  4. RUN npm install --production
  5. RUN npm run build
  6. EXPOSE 3000
  7. CMD ["npm", "start"]
复制代码
(2) Kubernetes 摆设文件
  1. apiVersion: apps/v1
  2. kind: Deployment
  3. metadata:
  4.   name: nuxt-app
  5. spec:
  6.   replicas: 3
  7.   selector:
  8.     matchLabels:
  9.       app: nuxt
  10.   template:
  11.     metadata:
  12.       labels:
  13.         app: nuxt
  14.     spec:
  15.       containers:
  16.       - name: nuxt
  17.         image: registry.cn-hangzhou.aliyuncs.com/your-repo/nuxt-app:latest
  18.         ports:
  19.         - containerPort: 3000
复制代码
2. 监控与告警

(1) 阿里云 ARMS 接入
  1. // 前端监控(Nuxt 插件)
  2. export default ({ app }, inject) => {
  3.   if (process.client) {
  4.     const BrowserLogger = require('alife-logger').Browser
  5.     const __bl = BrowserLogger.singleton({
  6.       pid: '你的项目ID',
  7.       appType: 'web',
  8.       imgUrl: 'https://arms-retcode.aliyuncs.com/r.png'
  9.     })
  10.     inject('arms', __bl)
  11.   }
  12. }
复制代码
(2) 非常告警规则


  • 指标:HTTP 错误率 > 5%
  • 动作:短信 + 钉钉群关照

五、项目复盘总结

1. 关键技能点



  • SSR 缓存计谋:通过页面级缓存扛住 5000+ QPS
  • 付出对账体系:逐日定时任务查对微信/付出宝账单
  • 分布式锁设计:使用 Redis 防止超卖
2. 典范标题与办理

标题场景办理方案微信付出 NAT 穿透失败使用阿里云 EIP 绑定服务器 + 付出回调域名存案首屏加载白屏时间长关键 CSS 内联 + 图片 WebP 转换 + 阿里云 DCDN 全站加速恶意刷单攻击接入阿里云 WAF + 滑动验证码(活动验证)3. 扩展练习



  • 秒杀体系:接入 RocketMQ 消息队列 + Redis 原子计数器
  • 物流追踪:集成快递鸟 API + 高德舆图轨迹绘制
  • 数据大屏:ECharts 及时展示订单量/用户地区分布

全文完
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表