马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
阶段一:基础认知与快速上手
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)。
- 安装后验证是否乐成:
- node -v # 应输出版本号(如 v18.16.0)
- npm -v # 应输出版本号(如 9.5.1)
复制代码 步骤 2:选择包管理工具(npm 或 yarn)
- 假如喜欢更快的速率,可安装 Yarn:
- npm install -g yarn
- yarn -v # 验证版本
复制代码 2.2 创建 Nuxt 项目
步骤 1:使用脚手架
- npx create-nuxt-app my-first-nuxt-app
复制代码
- 假如使用 Yarn:
- yarn create nuxt-app my-first-nuxt-app
复制代码 步骤 2:回答交互式标题
以下是保举小白选择的设置(方向键选择,回车确认):
- ? Programming language: JavaScript
- ? Package manager: Npm 或 Yarn(根据上一步选择)
- ? UI framework: None (先不用 UI 库,避免复杂度)
- ? Nuxt.js modules: None (后续手动添加)
- ? Linting tools: None (先跳过代码检查)
- ? Testing framework: None
- ? Rendering mode: Universal (SSR / SSG)
- ? Deployment target: Server (SSR)
- ? Development tools: jsconfig.json (可选)
- ? Continuous integration: None
- ? Version control system: Git
复制代码 步骤 3:启动开辟服务器
- cd my-first-nuxt-app
- npm run dev
- # 或 yarn dev
复制代码
- 访问 http://localhost:3000,你会看到默认接待页!
步骤 4:体验热重载 (Hot Reload)
- 打开 pages/index.vue,修改 <h1> 标签内的笔墨。
- 生存文件,欣赏器会主动革新表现最新内容。
3:解剖Nuxt项目结构
3.1 关键目次与文件
- my-first-nuxt-app/
- ├── pages/ # 页面组件,自动生成路由
- ├── layouts/ # 布局组件(如页头、页脚)
- ├── assets/ # 静态资源(CSS/图片/字体)
- ├── components/ # 可复用的 Vue 组件
- ├── nuxt.config.js # Nuxt 配置文件
- └── package.json # 项目依赖和脚本
复制代码 3.2 焦点文件详解
(1) pages/index.vue
- <template>
- <div>
- <h1>Welcome to Nuxt!</h1>
- </div>
- </template>
复制代码
(2) layouts/default.vue
- <template>
- <div>
- <NuxtPage /> <!-- 页面内容将插入此处 -->
- </div>
- </template>
复制代码
- 默认结构,所有页面默认使用此结构。
- <NuxtPage /> 是页面内容的占位符。
(3) nuxt.config.js
- export default {
- // 配置 Nuxt 的核心选项
- modules: [], // 添加模块
- css: [], // 全局 CSS 文件
- buildModules: [],// 开发环境模块
- }
复制代码 阶段二:页面开辟与路由基础
1. 创建你的第一个页面
步骤 1:新建 about 页面
- 在 pages/ 目次下创建 about.vue 文件:
- <template>
- <div>
- <h1>关于我们</h1>
- <p>这里是关于页面的内容。</p>
- </div>
- </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:
- <template>
- <header>
- <nav>
- <NuxtLink to="/">首页</NuxtLink>
- <NuxtLink to="/about">关于</NuxtLink>
- </nav>
- </header>
- </template>
- <style scoped>
- nav { padding: 20px; background: #f0f0f0; }
- a { margin-right: 15px; }
- </style>
复制代码 步骤 2:在页面中引入组件
修改 pages/index.vue:
- <template>
- <div>
- <Header /> <!-- 使用组件 -->
- <h1>Welcome to Nuxt!</h1>
- </div>
- </template>
- <script>
- import Header from '@/components/Header.vue' // 导入组件
- export default {
- components: { Header } // 注册组件
- }
- </script>
复制代码 3. 动态路由实战
步骤 1:创建动态路由页面
- 在 pages/ 下新建 users/_id.vue(留意下划线前缀):
- <template>
- <div>
- <h1>用户详情页</h1>
- <p>用户ID:{{ $route.params.id }}</p>
- </div>
- </template>
复制代码 - 访问 http://localhost:3000/users/123,页面表现用户ID:123。
步骤 2:使用 <NuxtLink> 跳转
在 Header.vue 中添加链接:
- <NuxtLink to="/users/456">用户456</NuxtLink>
复制代码 4. 结构体系精讲
步骤 1:自界说结构
- 创建 layouts/custom.vue:
- <template>
- <div>
- <Header />
- <main>
- <slot /> <!-- 页面内容插入点 -->
- </main>
- <footer style="margin-top: 50px; text-align: center;">
- <p>© 2023 我的网站</p>
- </footer>
- </div>
- </template>
- <script>
- import Header from '@/components/Header.vue'
- export default {
- components: { Header }
- }
- </script>
复制代码 步骤 2:指定页面使用结构
修改 pages/about.vue:
- <script>
- export default {
- layout: 'custom' // 使用自定义布局
- }
- </script>
复制代码 5. 导航组件进阶
使用 <NuxtLink> 的激活类
- 修改 Header.vue 样式:
- .nuxt-link-active {
- font-weight: bold;
- color: #42b983;
- }
复制代码 - 当前路由对应的链接会主动添加 nuxt-link-active 类。
本阶段练习任务
- 创建一个 /contact 页面,展示接洽方式。
- 实现动态路由 /posts/:slug,表现文章标题。
- 为所有页面添加全局页脚(通过默认结构修改)。
阶段三:数据获取与状态管理
1. 数据获取的两种焦点方式
Nuxt.js 提供两种异步数据获取方法:asyncData(服务端获取)和 fetch(客户端或服务端获取)。
(1) asyncData:服务端数据预获取
- 特性:在页面渲染前运行(服务端),SEO 友爱。
- 实用场景:必要 SEO 的页面数据(如商品详情页)。
- 示例:在 pages/posts/_id.vue 中:
- <template>
- <div>
- <h1>{{ post.title }}</h1>
- <p>{{ post.content }}</p>
- </div>
- </template>
- <script>
- export default {
- async asyncData({ params }) {
- // 模拟 API 请求
- const post = await $fetch(`https://api.example.com/posts/${params.id}`)
- return { post } // 返回的数据会合并到组件 data 中
- }
- }
- </script>
复制代码 (2) fetch:客户端或服务端获取
- 特性:可以在客户端或服务端运行,适合非关键数据。
- 示例:在 pages/index.vue 中:
- <script>
- export default {
- data() {
- return { products: [] }
- },
- async fetch() {
- this.products = await $fetch('https://api.example.com/products')
- }
- }
- </script>
复制代码 2. 使用 Axios 发送 HTTP 请求
步骤 1:安装 Axios 模块
- npm install @nuxtjs/axios
复制代码 步骤 2:设置 nuxt.config.js
- export default {
- modules: ['@nuxtjs/axios'],
- axios: {
- baseURL: 'https://api.example.com' // 基础 URL
- }
- }
复制代码 步骤 3:在组件中使用
- <script>
- export default {
- async asyncData({ $axios }) {
- const users = await $axios.$get('/users')
- return { users }
- }
- }
- </script>
复制代码 3. 状态管理:Pinia 入门
Pinia 是 Vue 官方保举的状态管理库,替代 Vuex。
步骤 1:安装 Pinia
步骤 2:设置 nuxt.config.js
- export default {
- modules: ['@pinia/nuxt']
- }
复制代码 步骤 3:创建 Store
- 新建 stores/counter.js:
- import { defineStore } from 'pinia'
- export const useCounterStore = defineStore('counter', {
- state: () => ({ count: 0 }),
- actions: {
- increment() {
- this.count++
- }
- }
- })
复制代码 步骤 4:在组件中使用
- <template>
- <div>
- <button @click="counter.increment">点击次数:{{ counter.count }}</button>
- </div>
- </template>
- <script>
- import { useCounterStore } from '~/stores/counter'
- export default {
- setup() {
- const counter = useCounterStore()
- return { counter }
- }
- }
- </script>
复制代码 4. 数据缓存与错误处理
(1) 使用 useAsyncData (Nuxt 3)
- <script setup>
- const { data, error } = await useAsyncData('posts', () => {
- return $fetch('https://api.example.com/posts')
- })
- if (error.value) {
- console.error('数据加载失败:', error.value)
- }
- </script>
复制代码 (2) 全局错误页面
- 创建 layouts/error.vue:
- <template>
- <div class="error-container">
- <h1 v-if="error.statusCode === 404">页面不存在</h1>
- <h1 v-else>发生错误:{{ error.message }}</h1>
- <NuxtLink to="/">返回首页</NuxtLink>
- </div>
- </template>
- <script>
- export default {
- props: ['error']
- }
- </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:
- export default {
- target: 'static' // 指定生成静态站点
- }
复制代码 - 构建并天生静态文件:
步骤 2:上传到阿里云 OSS
- 创建 OSS Bucket:
- 登录 阿里云控制台,创建 Bucket,选择「公共读」权限。
- 地区选择离用户近的(如华东1-杭州)。
- 上传文件:
- 在 OSS 控制台进入 Bucket,点击「上传文件」,将 dist/ 目次下的所有内容上传。
- 或使用下令行工具 ossutil:
- ossutil cp -r dist/ oss://你的Bucket名称/ --recursive
复制代码
- 绑定自界说域名(可选):
- 在 Bucket 的「域名管理」中绑定已存案的域名,并设置 CDN 加速。
3. 服务端渲染摆设实战(以腾讯云 CVM 为例)
步骤 1:服务器准备
- 购买腾讯云 CVM 实例(保举 CentOS 或 Ubuntu 体系)。
- 通过 SSH 毗连服务器:
步骤 2:摆设 Node.js 环境
- 安装 Node.js 和 npm:
- # Ubuntu/Debian
- curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
- sudo apt install -y nodejs
- # CentOS
- curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
- sudo yum install -y nodejs
复制代码 步骤 3:摆设 Nuxt 项目
- 将代码上传到服务器(使用 Git 或 SFTP 工具)。
- 安装依赖并构建:
- 使用 PM2 守护进程:
- npm install pm2 -g
- pm2 start "npm run start" --name nuxt-app
复制代码 4. 国内性能优化本领
(1) 图片优化
- 使用腾讯云数据万象(CI):
- 主动压缩、格式转换、缩略图天生。
- 在 nuxt.config.js 中设置图片域名:
- export default {
- image: {
- domains: ['你的Bucket.ci.tencentcloudcs.com']
- }
- }
复制代码
- 懒加载:
- <NuxtImg src="image.jpg" loading="lazy" />
复制代码 (2) CDN 加速
- 阿里云 CDN 或 腾讯云 CDN:
- 将静态资源(JS/CSS/图片)托管到 CDN,提拔访问速率。
- 在 nuxt.config.js 中设置资源路径:
- export default {
- build: {
- publicPath: 'https://你的CDN域名/_nuxt/'
- }
- }
复制代码
(3) 代码压缩与合并
- 启用 Brotli 压缩(需服务器支持):
- // nuxt.config.js
- export default {
- build: {
- compress: {
- brotli: true,
- gzip: true
- }
- }
- }
复制代码 (4) 缓存计谋
- OSS/COS 设置缓存头:
- 在对象存储控制台为静态文件设置 Cache-Control: max-age=31536000(1年)。
- API 请求缓存:
- // 使用内存缓存
- const cachedData = useState('data', () => null)
- if (!cachedData.value) {
- cachedData.value = await $fetch('/api/data')
- }
复制代码 5. 国内监控 与分析工具
- 性能监测:
- 阿里云 ARMS(应用及时监控
)
- 腾讯云前端性能监控
(RUM)
- SEO 分析:
- 错误追踪:
- Sentry 国内版(https://sentry.cn)
本阶段练习任务
- 将 Nuxt 项目摆设到 Gitee Pages(需关联码云堆栈并开启 Pages 服务)。
- 使用 腾讯云数据万象 对首页图片举行压缩和 WebP 格式转换。
- 通过 阿里云 CDN 加速静态资源,对比加速前后的加载速率。
阶段五:进阶实战与生态集成
1. 中心件(Middleware):路由守卫与权限控制
(1) 什么是中心件?
- 界说:在页面渲染前实行的代码,用于全局或页面级的逻辑处理(如身份验证、日志
记载)。
- 运行环境:服务端(SSR)或客户端(SPA)。
(2) 实战:实现登录拦截
- 创建中心件文件
在根目次新建 middleware/auth.js:
- export default function ({ redirect, store }) {
- // 假设 Pinia 存储用户状态
- if (!store.auth.isLoggedIn) {
- return redirect('/login') // 未登录跳转到登录页
- }
- }
复制代码 - 应用中心件
- 全局见效(在 nuxt.config.js 中设置):
- export default {
- router: { middleware: ['auth'] }
- }
复制代码 - 页面级见效(在页面组件中):
- <script>
- export default {
- middleware: 'auth' // 仅当前页面生效
- }
- </script>
复制代码
2. 插件开辟:扩展 Nuxt 本领
(1) 封装 Axios 拦截器(适配国内常见鉴权)
- 创建插件文件 plugins/axios.js:
- export default function ({ $axios, store }) {
- $axios.onRequest(config => {
- // 添加腾讯云鉴权头部(示例)
- config.headers['X-Signature'] = store.auth.token
- return config
- })
- $axios.onError(error => {
- if (error.response.status === 401) {
- // Token 过期跳转登录
- window.location.href = '/login?expired=1'
- }
- return Promise.reject(error)
- })
- }
复制代码 - 注册插件
在 nuxt.config.js 中:
- export default {
- plugins: ['@/plugins/axios']
- }
复制代码 (2) 集成微信 JS-SDK
- 安装依赖:
- npm install weixin-js-sdk
复制代码 - 创建插件 plugins/wx-sdk.js:
- import wx from 'weixin-js-sdk'
- export default ({ app }, inject) => {
- inject('wx', wx) // 全局注入 this.$wx
- }
复制代码 3. TypeScript 深度支持
(1) 启用 TypeScript
- 安装依赖:
- npm install @nuxt/typescript-build @nuxt/types --save-dev
复制代码 - 设置 nuxt.config.js:
- export default {
- buildModules: ['@nuxt/typescript-build']
- }
复制代码 - 创建范例声明文件 types/index.d.ts:
- import { User } from '~/types/user'
- declare module '@nuxt/types' {
- interface Context {
- $auth: User // 扩展上下文类型
- }
- }
复制代码 (2) 范例化 Pinia Store
修改 stores/counter.ts:
- import { defineStore } from 'pinia'
- interface CounterState {
- count: number
- }
- export const useCounterStore = defineStore('counter', {
- state: (): CounterState => ({ count: 0 }),
- actions: {
- increment() {
- this.count++
- }
- }
- })
复制代码 4. 集成国内 UI 框架:Vant
(1) 安装与设置
- 安装 Vant:
- npm install vant @vant/auto-import-resolver
复制代码 - 设置 nuxt.config.js:
- export default {
- buildModules: [
- ['@nuxtjs/vuetify', { autoImport: true }] // 自动按需引入
- ],
- css: ['vant/lib/index.css']
- }
复制代码 (2) 在组件中使用
- <template>
- <van-button type="primary" @click="submit">提交</van-button>
- </template>
- <script>
- // 无需手动导入,自动引入!
- export default {
- methods: {
- submit() { /* ... */ }
- }
- }
- </script>
复制代码 5. 百度 SEO 优化实战
(1) 主动天生 sitemap
- 安装模块:
- npm install @nuxtjs/sitemap
复制代码 - 设置 nuxt.config.js:
- export default {
- modules: ['@nuxtjs/sitemap'],
- sitemap: {
- hostname: 'https://你的域名.com',
- routes: async () => {
- // 动态生成路由(如从 API 获取)
- return ['/about', '/contact']
- }
- }
- }
复制代码 (2) 百度主动推送
在 nuxt.config.js 中添加:
- export default {
- head: {
- script: [
- {
- src: 'https://zz.bdstatic.com/linksubmit/push.js', // 百度推送 JS
- async: true
- }
- ]
- }
- }
复制代码 本阶段练习任务
- 开辟一个中心件:实现管理员权限控制(/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)
- 初始化项目:
- npm init midway@latest -y
复制代码 选择 koa-v3 模板。
- 创建商品查询接口:
src/controller/product.controller.ts:
- import { Controller, Get, Inject } from '@midwayjs/core'
- import { Context } from '@midwayjs/koa'
- @Controller('/api/product')
- export class ProductController {
- @Inject()
- ctx: Context
- @Get('/:id')
- async getProduct(): Promise<any> {
- const id = this.ctx.params.id
- // 模拟数据库查询
- return { code: 200, data: { id, name: `商品${id}`, price: 99.9 } }
- }
- }
复制代码 - 当地运行:
访问 http://localhost:7001/api/product/123 测试接口。
(2) 前端 Nuxt.js 集成
- 设置署理办理跨域:
nuxt.config.js:
- export default {
- modules: ['@nuxtjs/axios'],
- axios: {
- proxy: true // 开启代理
- },
- proxy: {
- '/api/': {
- target: 'http://localhost:7001',
- pathRewrite: { '^/api/': '' }
- }
- }
- }
复制代码 - 页面调用接口:
pages/product/_id.vue:
- <template>
- <div>
- <h1>{{ product.name }}</h1>
- <p>价格:{{ product.price }}元</p>
- </div>
- </template>
- <script>
- export default {
- async asyncData({ $axios, params }) {
- const { data } = await $axios.get(`/api/product/${params.id}`)
- return { product: data }
- }
- }
- </script>
复制代码 3. 微服务架构实战(阿里云函数盘算)
(1) 将 Midway 后端摆设为 Serverless
- 安装 Serverless 工具:
- npm install @midwayjs/serverless-scf -g
复制代码 - 设置 f.yml:
- service:
- name: nuxt-demo-backend
- provider:
- name: aliyun
- region: cn-hangzhou
- functions:
- product:
- handler: product.default
- events:
- - http:
- path: /api/product/{id}
- method: get
复制代码 - 摆设到阿里云:
(2) 前端对接云函数
修改 nuxt.config.js 署理设置:
- proxy: {
- '/api/': {
- target: 'https://你的云函数网关地址',
- pathRewrite: { '^/api/': '' }
- }
- }
复制代码 4. 微前端架构集成(qiankun)
(1) 主应用设置(Nuxt.js)
- 安装 qiankun:
- 主应用入口插件 plugins/qiankun.js:
- import { registerMicroApps, start } from 'qiankun'
- export default ({ app }) => {
- registerMicroApps([
- {
- name: 'vue-subapp',
- entry: '//子应用域名/subapp/',
- container: '#subapp-container',
- activeRule: '/subapp'
- }
- ])
- start()
- }
复制代码 - 在结构中添加容器:
- <template>
- <div id="main-app">
- <Header />
- <div id="subapp-container"></div>
- </div>
- </template>
复制代码 (2) 子应用(Vue.js)适配
- 导出生命周期钩子:
subapp/src/public-path.js:
- if (window.__POWERED_BY_QIANKUN__) {
- __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
- }
复制代码 - 修改入口文件:
- import './public-path'
- import Vue from 'vue'
- import App from './App.vue'
- let instance = null
- function render(props = {}) {
- const { container } = props
- instance = new Vue({
- render: h => h(App)
- }).$mount(container ? container.querySelector('#app') : '#app')
- }
- // 独立运行时
- if (!window.__POWERED_BY_QIANKUN__) {
- render()
- }
- export async function bootstrap() {}
- export async function mount(props) { render(props) }
- export async function unmount() { instance.$destroy() }
复制代码 5. 连续集成与摆设(CI/CD)
(1) 使用 GitLab CI 主动化摆设
- 编写 .gitlab-ci.yml:
- stages: - build - deploycache: paths: - node_modules/build_frontend: stage: build image: node:16 script: - npm install - npm run generate
- 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:
- import oss2
- auth = oss2.Auth('你的AK', '你的SK')
- bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'bucket名称')
- for root, dirs, files in os.walk('dist'):
- for file in files:
- local_path = os.path.join(root, file)
- remote_path = local_path.replace('dist/', '')
- bucket.put_object_from_file(remote_path, local_path)
复制代码 本阶段练习任务
- 全栈实战:基于 Nuxt + Midway 实现一个商品管理体系(增编削查)。
- 微服务拆分:将用户模块拆分为独立云函数并集成。
- 微前端改造:将背景管理模块作为子应用接入 qiankun 主应用。
- CI/CD 实战:设置 GitLab CI 实现主动摆设到阿里云 OSS。
阶段七:性能调优与安全加固
一、性能调优进阶
1. 服务端性能优化
国内场景痛点:高并发访问、南北网络延迟差别
办理方案:
- (1) 服务端渲染缓存(SSR Cache)
- // nuxt.config.js
- export default {
- render: {
- http2: { push: true }, // 开启 HTTP/2 推送
- static: { maxAge: 1000 * 60 * 60 * 24 }, // 静态资源缓存
- cdn: {
- use: true, // 启用 CDN
- domain: 'https://你的阿里云CDN域名'
- }
- }
- }
复制代码 - (2) 使用 Redis 缓存热门数据
- // 阿里云 Redis 连接示例(需安装 ioredis)
- import Redis from 'ioredis'
- const redis = new Redis({
- host: '阿里云Redis实例地址',
- port: 6379,
- password: '你的密码'
- })
- // Nuxt 插件中缓存接口数据
- export default async ({ $axios }, inject) => {
- inject('cacheGet', async (key, url) => {
- const cached = await redis.get(key)
- if (cached) return JSON.parse(cached)
- const data = await $axios.$get(url)
- await redis.setex(key, 3600, JSON.stringify(data)) // 缓存1小时
- return data
- })
- }
复制代码 2. 客户端性能优化
国内场景痛点:弱网环境、低端安卓装备兼容性
办理方案:
- (1) 首屏关键 CSS 内联
- // nuxt.config.js
- export default {
- build: {
- extractCSS: {
- ignoreOrder: true,
- inline: ['app.css'] // 内联关键 CSS
- }
- }
- }
复制代码 - (2) 按需加载第三方库(如高德舆图)
- // plugins/amap.js
- export default ({ app }, inject) => {
- inject('loadAMap', () => {
- return new Promise((resolve) => {
- if (window.AMap) return resolve(window.AMap)
- const script = document.createElement('script')
- script.src = 'https://webapi.amap.com/maps?v=2.0&key=你的高德地图Key'
- script.onload = () => resolve(window.AMap)
- document.head.appendChild(script)
- })
- })
- }
复制代码 3. 数据库优化
国内云服务集成:
- 阿里云 PolarDB(兼容 MySQL,主动弹性扩展)
- 腾讯云 TDSQL-C(Serverless 数据库)
优化本领:
- -- 示例:添加索引提升查询速度
- ALTER TABLE products
- ADD INDEX idx_category_status (category_id, status);
复制代码 二、安全加固实战
1. 基础安全防护
(1) HTTPS 逼迫跳转
- 国内免费 SSL 证书:
- 阿里云 SSL 证书(免费 DV 版)
- 腾讯云 TrustAsia 免费证书
- Nginx 设置:
- server {
- listen 80;
- server_name yourdomain.com;
- return 301 https://$server_name$request_uri;
- }
复制代码 (2) 防止 XSS 攻击
- CSP 内容安全计谋:
- // nuxt.config.js
- export default {
- head: {
- meta: [
- {
- 'http-equiv': 'Content-Security-Policy',
- content: `default-src 'self' https://*.aliyuncs.com; script-src 'self' 'unsafe-inline' https://unpkg.com`
- }
- ]
- }
- }
复制代码 2. 接口安全防护
(1) CSRF Token 校验
- // 使用 @nuxtjs/axios 模块配置
- export default {
- axios: {
- credentials: true,
- baseURL: process.env.API_BASE_URL,
- proxyHeaders: false,
- retry: { retries: 3 }
- },
- modules: ['@nuxtjs/axios'],
- // 生成 CSRF Token
- serverMiddleware: [
- { path: '/api/csrf', handler: '~/server-middleware/csrf.js' }
- ]
- }
复制代码 (2) 敏感数据脱敏
- // 使用中间件过滤敏感字段
- export default function ({ res }) {
- res.setHeader('X-Content-Type-Options', 'nosniff')
- res.setHeader('X-XSS-Protection', '1; mode=block')
- }
复制代码 3. 防爬虫与 CC 攻击
国内工具保举:
- 阿里云 WAF(Web 应用防火墙)
- 腾讯云天御防爬服务
设置示例:
- // 在 Nuxt 中识别爬虫并拦截
- export default function (req, res, next) {
- const userAgent = req.headers['user-agent']
- const isBot = /bot|spider|crawl|scraping/i.test(userAgent)
- if (isBot) {
- res.statusCode = 403
- return res.end('Forbidden')
- }
- next()
- }
复制代码 三、合规与监控
1. 等保 2.0 合规要求
- 日志
留存:使用阿里云日志 服务(SLS)存储 6 个月以上
- 审计追踪:接入阿里云 ActionTrail
- 数据加密:启用阿里云 KMS 密钥管理
2. 及时监控方案
国内保举组合:
- 前端监控:阿里云前端监控(FMP)
- 错误追踪:Sentry 国内版(sentry.io)
- API 监控:腾讯云 APM
设置示例(阿里云 FMP):
- // nuxt.config.js
- export default {
- head: {
- script: [
- {
- src: 'https://g.alicdn.com/sd/sentry/loader/your-sdk.js',
- async: true,
- onload: `Sentry.init({ dsn: '你的DSN' })`
- }
- ]
- }
- }
复制代码 四、实战练习
- 性能调优:
- 将 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. 架构图
- 用户浏览器 → 阿里云 CDN(缓存静态资源) → 阿里云 SLB → Nuxt 服务集群(SSR)
- ↓
- Midway 微服务集群(订单/支付/商品)
- ↓
- 阿里云 RDS(MySQL) + Redis(缓存/分布式锁)
复制代码 2. 微服务拆分
服务名称功能形貌技能实现商品服务商品详情、搜索、分类Midway.js + MySQL订单服务下单、付出状态回调、超时关闭Midway.js + Redis 分布式锁用户服务登录、权限管理、地址簿Midway.js + JWT付出服务聚合微信/付出宝付出、对账Midway.js + 微信付出 SDK 三、实战开辟步骤
1. 商品模块开辟(SSR 极致优化)
(1) 商品详情页 SSR 缓存
- // nuxt.config.js
- export default {
- render: {
- ssrCache: {
- max: 1000, // 缓存 1000 个页面
- ttl: 60 * 1000 // 缓存 1 分钟
- }
- }
- }
复制代码 (2) 图片懒加载 + WebP 主动转换
- <template>
- <NuxtImg
- src="/product.jpg"
- :modifiers="{ format: 'webp' }"
- loading="lazy"
- provider="aliyun"
- />
- </template>
复制代码 2. 用户认证(国内手机号+微信)
(1) 短信登录(阿里云 SMS)
- // Midway 控制器
- @Post('/sms/login')
- async smsLogin(@Body() { phone, code }) {
- const cacheCode = await redis.get(`sms:${phone}`)
- if (code !== cacheCode) throw new Error('验证码错误')
- const user = await userService.findOrCreate(phone)
- return { token: generateJWT(user.id) }
- }
复制代码 (2) 微信授权登录
- // Nuxt 插件
- export default ({ app }, inject) => {
- inject('wechatLogin', () => {
- const redirectUri = encodeURIComponent('https://你的域名/auth/wechat')
- window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo`
- })
- }
复制代码 3. 订单付出(微信+付出宝聚合)
(1) 微信付出同一下单
- // Midway 支付服务
- async createWechatPay(order) {
- const result = await wxpay.unifiedOrder({
- body: order.title,
- out_trade_no: order.no,
- total_fee: order.amount * 100,
- openid: order.user.openid
- })
- return {
- paymentUrl: result.mweb_url,
- paySign: result.sign
- }
- }
复制代码 (2) 付出效果回调校验
- @Post('/pay/notify/wechat')
- async wechatNotify(@Body() xmlData) {
- const result = await wxpay.verifySign(xmlData)
- if (result.return_code === 'SUCCESS') {
- await orderService.completePayment(result.out_trade_no)
- }
- return '<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>'
- }
复制代码 四、摆设与运维
1. 容器化摆设(阿里云 ACK)
(1) Dockerfile 设置
- FROM node:16-alpine
- WORKDIR /app
- COPY . .
- RUN npm install --production
- RUN npm run build
- EXPOSE 3000
- CMD ["npm", "start"]
复制代码 (2) Kubernetes 摆设文件
- apiVersion: apps/v1
- kind: Deployment
- metadata:
- name: nuxt-app
- spec:
- replicas: 3
- selector:
- matchLabels:
- app: nuxt
- template:
- metadata:
- labels:
- app: nuxt
- spec:
- containers:
- - name: nuxt
- image: registry.cn-hangzhou.aliyuncs.com/your-repo/nuxt-app:latest
- ports:
- - containerPort: 3000
复制代码 2. 监控与告警
(1) 阿里云 ARMS 接入
- // 前端监控(Nuxt 插件)
- export default ({ app }, inject) => {
- if (process.client) {
- const BrowserLogger = require('alife-logger').Browser
- const __bl = BrowserLogger.singleton({
- pid: '你的项目ID',
- appType: 'web',
- imgUrl: 'https://arms-retcode.aliyuncs.com/r.png'
- })
- inject('arms', __bl)
- }
- }
复制代码 (2) 非常告警规则
- 指标:HTTP 错误率 > 5%
- 动作:短信 + 钉钉群关照
五、项目复盘总结
1. 关键技能点
- SSR 缓存计谋:通过页面级缓存扛住 5000+ QPS
- 付出对账体系:逐日定时任务查对微信/付出宝账单
- 分布式锁设计:使用 Redis 防止超卖
2. 典范标题与办理
标题场景办理方案微信付出 NAT 穿透失败使用阿里云 EIP 绑定服务器 + 付出回调域名存案首屏加载白屏时间长关键 CSS 内联 + 图片 WebP 转换 + 阿里云 DCDN 全站加速恶意刷单攻击接入阿里云 WAF + 滑动验证码(活动验证)3. 扩展练习
- 秒杀体系:接入 RocketMQ 消息队列 + Redis 原子计数器
- 物流追踪:集成快递鸟 API + 高德舆图轨迹绘制
- 数据大屏:ECharts 及时展示订单量/用户地区分布
全文完
|