本文面向熟悉Java + SpringBoot技术栈的后端开发工程师,通过一个用户登录页面的Demo项目,快速掌握HTML/CSS/JavaScript语法基础、TypeScript类型系统,以及Vue3框架(组合式API)的基础使用。
技术栈对照 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ┌──────────────────────────────────────────────────────────────────┐ │ 后端(Java) vs 前端技术栈对照 │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ 后端Java技术栈 前端技术栈 │ │ ───────────────────────────────────────────────────────────── │ │ 运行环境 JVM 浏览器(V8/JavaScriptCore) │ │ 包管理 Maven/Gradle npm / pnpm / yarn │ │ 构建工具 Maven/Gradle Vite / Webpack │ │ 依赖描述 pom.xml package.json │ │ 锁文件 - package-lock.json / pnpm-lock.yaml│ │ 语言 Java HTML + CSS + JavaScript │ │ 静态类型(编译期检查) 动态类型(TS可补充类型) │ │ 框架 SpringBoot Vue / React / Angular │ │ 模板引擎 Thymeleaf/Freemarker Vue 模板(SFC中的template) │ │ 依赖注入 Spring IoC provide/inject(组件级) │ │ 路由 Spring MVC @RequestMapping vue-router │ │ 全局状态 - Pinia / Vuex │ │ HTTP客户端 RestTemplate/Feign axios / fetch │ │ 单元测试 JUnit Vitest / Jest │ │ 打包产物 jar/war HTML+JS+CSS 静态资源 │ │ 部署 运行在服务器上 部署到Nginx/CDN,运行在浏览器 │ │ │ └──────────────────────────────────────────────────────────────────┘
最关键的心智转变 :后端代码运行在”你完全掌控”的服务器上,前端代码运行在”你不掌控”的用户浏览器里。因此前端的一切数据都不可信、一切网络请求都可能失败、任何写在代码里的密钥都等于公开。
项目结构与工程化 一个前后端项目的目录对照 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ┌──────────────────────────────────────────────────────────────────┐ │ 项目目录结构对照 │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ SpringBoot项目 Vue3 + Vite项目 │ │ ──────────────────── ──────────────────── │ │ src/main/java/ src/ │ │ ├── com/example/ ├── main.js (入口) │ │ │ ├── controller/ ├── App.vue (根组件) │ │ │ ├── service/ ├── router/ │ │ │ └── Application.java │ └── index.js │ │ ├── resources/ ├── stores/ │ │ │ ├── application.yml │ └── user.js │ │ │ └── static/ ├── api/ │ │ └── test/ │ └── user.js │ │ ├── views/ │ │ pom.xml │ ├── LoginView.vue │ │ │ └── HomeView.vue │ │ ├── components/ │ │ │ └── UserCard.vue │ │ └── assets/ │ │ └── main.css │ │ index.html │ │ package.json │ │ vite.config.js │ │ .env.development │ │ │ │ 注意:前端项目根目录下的 index.html 是页面模板, │ │ 而 src/ 下才是源码;二者不是一回事。 │ │ │ └──────────────────────────────────────────────────────────────────┘
创建项目 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 node -v npm -v npm create vue@latest user-login-web cd user-login-webnpm install npm run dev npm create vite@latest user-login-web -- --template vue cd user-login-webnpm install npm run dev npm run dev npm run build npm run preview
package.json(对应 pom.xml) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { "name" : "user-login-web" , "version" : "0.0.1" , "type" : "module" , "scripts" : { "dev" : "vite" , "build" : "vite build" , "preview" : "vite preview" } , "dependencies" : { "vue" : "^3.4.0" , "vue-router" : "^4.3.0" , "pinia" : "^2.1.7" , "axios" : "^1.6.0" } , "devDependencies" : { "vite" : "^5.0.0" , "@vitejs/plugin-vue" : "^5.0.0" } }
依赖分类对照 :
概念
Maven
npm
依赖描述
<dependencies>
dependencies
只在开发/构建期用、不进产物的依赖
<scope>test</scope> / <scope>provided</scope>
devDependencies
版本范围
[1.0,2.0)
^1.2.3(兼容版本)、~1.2.3(补丁版本)
安装全部依赖
mvn install
npm install
添加依赖
手写 pom 后 mvn install
npm install axios
本地仓库
~/.m2/repository
node_modules/(在项目内)
运行脚本
maven plugins
npm run xxx
HTML基础 什么是HTML HTML(HyperText Markup Language)是页面的结构 ,用标签描述”页面上有什么”。它没有逻辑,只有嵌套的标签树——本质上和你在后端写的 XML/DOM 解析树是同一类东西。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <!DOCTYPE html > <html lang ="zh-CN" > <head > <meta charset ="UTF-8" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <title > 用户登录</title > <link rel ="stylesheet" href ="/style.css" > </head > <body > <h1 > 欢迎登录</h1 > <p > 请输入你的账号信息</p > <script src ="/app.js" > </script > </body > </html >
常用标签 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 <h1 > 一级标题</h1 > <h2 > 二级标题</h2 > <p > 段落文本</p > <span > 行内文本,不换行</span > <strong > 加粗强调</strong > <em > 斜体强调</em > <br /> <hr /> <header > 页面头部</header > <nav > 导航栏</nav > <main > 主体内容</main > <section > 内容区块</section > <article > 独立文章</article > <aside > 侧边栏</aside > <footer > 页面底部</footer > <div > 通用块级容器</div > <span > 通用行内容器</span > <a href ="https://example.com" > 外部链接</a > <a href ="/home" > 站内链接</a > <a href ="/home" target ="_blank" > 新标签页打开</a > <img src ="/logo.png" alt ="网站Logo" /> <ul > <li > 无序列表项</li > </ul > <ol > <li > 有序列表项</li > </ol > <form action ="/api/login" method ="post" > <label for ="username" > 用户名</label > <input id ="username" name ="username" type ="text" placeholder ="请输入用户名" /> <label for ="password" > 密码</label > <input id ="password" name ="password" type ="password" /> <select name ="role" > <option value ="user" > 普通用户</option > <option value ="admin" > 管理员</option > </select > <textarea name ="remark" rows ="3" > </textarea > <input type ="checkbox" id ="remember" /> <label for ="remember" > 记住我</label > <button type ="submit" > 登录</button > </form >
标签属性 1 2 3 4 5 6 7 8 9 10 11 12 13 <div id ="app" > </div > <p class ="text primary" > 一段文本</p > <div data-user-id ="123" > 用户信息</div >
1 2 <input type ="checkbox" checked disabled />
1 2 3 4 5 <input name ="username" /> <input required minlength ="3" /> <button type ="submit" > 提交</button > <button type ="button" > 普通按钮(不会提交表单)</button >
常用标签速查 :
标签
用途
常见属性
a
超链接
href target
img
图片
src alt
input
输入框
type name value placeholder disabled required
button
按钮
type disabled
form
表单容器
action method
table
表格
内部用 thead tbody tr th td
ul / ol
列表
内部用 li
div / span
通用容器
块级 / 行内
template
不渲染的模板
Vue 中大量使用
CSS基础 什么是CSS CSS(Cascading Style Sheets)负责页面的样式 ,即”长什么样”。它的核心是选择器 + 声明块 :选中一批元素,给它们设置属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 p { color : #333333 ; font-size : 14px ; } .card { border : 1px solid #ddd ; border-radius : 8px ; padding : 16px ; } #app { max-width : 1200px ; margin : 0 auto; } .card .title { } .card > .title { } .card .active { } input [type="text" ] { } a :hover { } input :focus { } li :nth-child (2 ) { } li :first-child { } button :disabled { } p ::first-line { }.clearfix ::after { content : "" ; display : block; clear : both; }
引入CSS的三种方式 1 2 3 4 5 6 7 <link rel ="stylesheet" href ="/style.css" /> <style > body { margin : 0 ; } </style >
1 2 <div style ="color: red; margin-top: 10px;" > 文本</div >
盒模型 每个元素都可以看作一个盒子,从内到外是:content → padding → border → margin。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ┌──────────────────────────────────────────────────────────────────┐ │ 盒模型(Box Model) │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ margin(外边距,与相邻元素的间距)─ ─ ─ ┐ │ │ │ ┌───────────────────────────────────────────────┐ │ │ │ │ │ border(边框,1px solid #ddd) │ │ │ │ │ │ ┌───────────────────────────────────────┐ │ │ │ │ │ │ │ padding(内边距,内容与边框的距离)│ │ │ │ │ │ │ │ ┌───────────────────────────────┐ │ │ │ │ │ │ │ │ │ content(内容:宽x高) │ │ │ │ │ │ │ │ │ └───────────────────────────────┘ │ │ │ │ │ │ │ └───────────────────────────────────────┘ │ │ │ │ │ └───────────────────────────────────────────────┘ │ │ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ │ │ │ │ 关键:box-sizing │ │ • content-box(默认):width 只算 content, 加padding会把盒子撑大│ │ • border-box(推荐):width = content+padding+border,所见即所得 │ │ 通常全局设置:* { box-sizing: border-box; } │ │ │ └──────────────────────────────────────────────────────────────────┘
1 2 3 4 5 6 7 8 9 10 margin : 10px 20px 10px 20px ;padding : 10px 20px ; margin : 0 auto; border-radius : 8px ;box-shadow : 0 2px 8px rgba (0 , 0 , 0 , 0.1 );
布局:Flexbox(重点) Flex 是现代前端最常用的布局方式,理解它就能解决大部分”怎么摆”的问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ┌──────────────────────────────────────────────────────────────────┐ │ Flexbox 布局模型 │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ .container { display: flex; } │ │ │ │ → 主轴方向由 flex-direction 决定(默认 row,横向) │ │ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ ← 主轴 main axis(justify-content 控制)→ │ │ │ │ ┌────────┐ ┌────────┐ ┌────────┐ │ │ │ │ │ item 1 │ │ item 2 │ │ item 3 │ ↕ 交叉轴 │ │ │ │ └────────┘ └────────┘ └────────┘ (align-items) │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ │ 容器属性(写在父元素上): │ │ • display: flex 变成flex容器 │ │ • flex-direction 主轴方向:row|column │ │ • justify-content 主轴对齐:flex-start|center| │ │ space-between|space-around|flex-end │ │ • align-items 交叉轴对齐:stretch|center|flex-start │ │ • flex-wrap 换行:nowrap|wrap │ │ • gap 子元素间距 │ │ │ │ 子元素属性: │ │ • flex: 1 占满剩余空间(做等分布局) │ │ • flex-shrink 空间不足时是否压缩 │ │ • align-self 覆盖父元素的align-items │ │ │ └──────────────────────────────────────────────────────────────────┘
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 .center { display : flex; justify-content : center; align-items : center; min-height : 100vh ; } .navbar { display : flex; justify-content : space-between; align-items : center; height : 60px ; padding : 0 24px ; } .card-row { display : flex; gap : 16px ; } .card-row > .card { flex : 1 ; } .layout { display : flex; } .layout > .sidebar { width : 220px ; flex-shrink : 0 ; } .layout > .main { flex : 1 ; min-width : 0 ; }
布局:Grid(补充) Grid 适合二维布局(行和列同时控制),Flex 更适合一维。
1 2 3 4 5 6 7 8 9 10 11 12 .grid { display : grid; grid-template-columns : repeat (3 , 1 fr); gap : 16px ; } .responsive-grid { display : grid; grid-template-columns : repeat (auto-fill, minmax (240px , 1 fr)); gap : 16px ; }
定位与层叠 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 .modal-mask { position : fixed; inset : 0 ; background : rgba (0 , 0 , 0 , 0.5 ); display : flex; justify-content : center; align-items : center; z-index : 1000 ; }
层叠与优先级 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ┌──────────────────────────────────────────────────────────────────┐ │ 样式冲突时谁生效(优先级) │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ 1. !important 最高(尽量别用) │ │ 2. 行内样式 style="..." │ │ 3. #id 选择器 权重 100 │ │ 4. .class / [attr] / :hover 权重 10 │ │ 5. 标签选择器 / ::伪元素 权重 1 │ │ 6. 通配符 * 权重 0 │ │ │ │ 规则:权重相加比较,权重相同则"后写的覆盖先写的"(层叠) │ │ │ │ CSS本质是"全局的":一个文件里的 .title 可能影响整个项目。 │ │ 这就是为什么 Vue 提供了 <style scoped>。 │ │ │ └──────────────────────────────────────────────────────────────────┘
常用单位与颜色 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 .box { width : 320px ; width : 50% ; width : 20rem ; width : 20em ; width : 100vw ; height : 100vh ; color : #ff5722 ; color : #f572 ; color : rgb (255 , 87 , 34 ); color : rgba (255 , 87 , 34 , 0.5 ); color : hsl (14 , 100% , 57% ); } body { font-family : -apple-system, "PingFang SC" , "Microsoft YaHei" , sans-serif; font-size : 14px ; font-weight : 500 ; line-height : 1.6 ; text-align : center; letter-spacing : 0.5px ; } .ellipsis { overflow : hidden; white-space : nowrap; text-overflow : ellipsis; }
过渡与动画(提升体验) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 .btn { background : #1677ff ; transition : all 0.2s ease; } .btn :hover { background : #4096ff ; transform : translateY (-2px ); } @keyframes fade-in { from { opacity : 0 ; transform : translateY (10px ); } to { opacity : 1 ; transform : translateY (0 ); } } .fade-in { animation : fade-in 0.3s ease-in-out; }
响应式:媒体查询 1 2 3 4 5 6 7 8 9 10 11 12 .card { padding : 12px ; }@media (min-width : 768px ) { .card { padding : 24px ; } } @media (min-width : 1200px ) { .card { padding : 32px ; } }
JavaScript基础 什么是JavaScript JavaScript 负责页面的行为 ,即”点击后发生什么”。它是动态类型的脚本语言,语法上借用了一些 Java 式的表象({}、类、try-catch),但核心模型完全不同(注意:=== 是 JS 自己的运算符,Java 里只有 == 和 equals)。
执行模型的最大区别 :JS 是单线程 + 事件循环 。没有 Thread、没有 synchronized,所有异步操作(网络请求、定时器)都靠回调/Promise 排队执行。所以你在后端习惯的”开个线程去请求”在这里没有对应物。
变量与类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 let name = "张三" ; const age = 25 ; var oldStyle = "不要用" ; let value = 1 ;value = "现在变成字符串了" ; const msg = `用户 ${name} 今年 ${age} 岁` ;const multi = `可以 跨多行` ;typeof name typeof age typeof undefinedVar if (value == null ) { } if (value === null ) { }
基本类型对照 :
Java
JavaScript
说明
String
string
不可变,单/双/反引号均可
int / long
number
只有一种数字类型,双精度浮点
double
number
0.1 + 0.2 !== 0.3,金额计算需注意
boolean
boolean
null
null / undefined
两个空值,== null 同时覆盖两者
char
string
没有单独的char
BigDecimal
-(需引入库)
金额常用 decimal.js 或后端返回字符串
Object
object / unknown
顶类型,使用前必须先收窄;any 会放弃类型检查,慎用
接口/泛型
TypeScript
需要 .ts 和编译步骤
松散相等 == 的坑 (务必用 ===):
1 2 3 4 5 1 == "1" 1 === "1" 0 == false 0 === false null == undefined
函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 function sayHello (name ) { return "Hello, " + name; } const sayHello2 = function (name ) { return "Hello, " + name; }; const sayHello3 = (name ) => { return "Hello, " + name; }; const sayHello4 = (name ) => `Hello, ${name} ` ; function greet (name = "访客" , greeting = "你好" ) { return `${greeting} , ${name} ` ; } greet (); greet ("张三" ); function sum (...nums ) { return nums.reduce ((a, b ) => a + b, 0 ); } sum (1 , 2 , 3 ); [1 , 2 , 3 ].forEach ((item ) => { console .log (item); });
对象(替代Class的常用写法) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 const user = { id : 1 , username : "admin" , email : "admin@example.com" , sayHi ( ) { return `我是 ${this .username} ` ; }, }; console .log (user.username ); console .log (user["username" ]); user.email = "new@example.com" ; user.age = 25 ; const { username, email } = user;const { username : name2, age = 18 } = user; const updated = { ...user, email : "changed@example.com" , age : 26 };const city = user?.address ?.city ; const displayName = user.nickname ?? user.username ;
数组常用方法 (对应 Java 的 Stream API):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 const users = [ { id : 1 , name : "张三" , age : 25 , status : 1 }, { id : 2 , name : "李四" , age : 30 , status : 0 }, { id : 3 , name : "王五" , age : 28 , status : 1 }, ]; const names = users.map ((u ) => u.name ); const activeUsers = users.filter ((u ) => u.status === 1 );const user = users.find ((u ) => u.id === 2 );const hasAdmin = users.some ((u ) => u.name === "管理员" );const allAdult = users.every ((u ) => u.age >= 18 );const totalAge = users.reduce ((sum, u ) => sum + u.age , 0 );const sorted = [...users].sort ((a, b ) => b.age - a.age );const result = users .filter ((u ) => u.status === 1 ) .map ((u ) => u.name ) .join ("、" ); users.length ; users.push ({ id : 4 , name : "赵六" }); users.findIndex ((u ) => u.id === 2 );
类(需要时也可以用) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class User { id; username; constructor (id, username ) { this .id = id; this .username = username; } getInfo ( ) { return `${this .id} : ${this .username} ` ; } static create (name ) { return new User (1 , name); } } class AdminUser extends User { constructor (id, username, level ) { super (id, username); this .level = level; } getInfo ( ) { return `[管理员] ${super .getInfo()} ` ; } } const admin = new AdminUser (1 , "admin" , 9 );
实际 Vue 开发中很少写 class,绝大多数场景用对象字面量 + 组合式函数就够了。class 主要在用第三方库时遇到。
异步编程(重点) 这是后端工程师最容易卡住的地方。JS 的网络请求不会阻塞后续代码 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 fetch ("/api/user/1" );console .log ("这行会先执行" );fetch ("/api/user/1" ) .then ((response ) => response.json ()) .then ((user ) => console .log (user)) .catch ((error ) => console .error (error)) .finally (() => console .log ("请求结束" )); async function loadUser (id ) { try { const response = await fetch (`/api/user/${id} ` ); if (!response.ok ) { throw new Error (`请求失败: ${response.status} ` ); } const data = await response.json (); return data; } catch (error) { console .error ("加载用户失败" , error); throw error; } } loadUser (1 ).then ((user ) => console .log (user));
并发请求(对应 Java 的 CompletableFuture.allOf) :
1 2 3 4 5 6 7 8 9 10 const [profile, orders, coupons] = await Promise .all ([ getProfile (), getOrders (), getCoupons (), ]); const results = await Promise .allSettled ([getProfile (), getOrders ()]);const ok = results.filter ((r ) => r.status === "fulfilled" );
易错点:循环中 await
1 2 3 4 5 6 7 for (const id of ids) { await loadUser (id); } await Promise .all (ids.map ((id ) => loadUser (id)));
DOM操作与事件(理解原理,Vue中很少手写) Vue 会替你操作 DOM,但理解这一层有助于排查问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 const el = document .querySelector (".card-title" ); const list = document .querySelectorAll (".item" ); const byId = document .getElementById ("app" );el.textContent = "新文本" ; el.innerHTML = "<b>加粗</b>" ; el.classList .add ("active" ); el.style .color = "red" ; el.setAttribute ("data-id" , "1" ); const div = document .createElement ("div" );div.textContent = "新元素" ; document .body .appendChild (div);const btn = document .querySelector ("#login-btn" );btn.addEventListener ("click" , (event ) => { console .log ("被点击了" , event.target ); event.preventDefault (); event.stopPropagation (); });
⚠️ 安全提示 :innerHTML 会把内容当 HTML 解析,用户输入里的 <img src=x onerror=...> 这类事件属性会直接执行 ,导致 XSS 攻击(注意:通过 innerHTML 插入的 <script> 标签本身不会执行,真正危险的是事件属性)。Vue 的 {{ }} 插值是转义的,但 v-html 不是,使用 v-html 时必须确保内容可信。
模块化(对应 Java 的 package + import) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 export function formatDate (date ) { return date.toLocaleDateString ("zh-CN" ); } export const MAX_SIZE = 1024 ;export default function request (url, options ) { } import { formatDate, MAX_SIZE } from "@/utils/format" ;import request from "@/utils/format" ;import request, { formatDate as fmt } from "@/utils/format" ;import * as formatUtils from "@/utils/format" ;formatUtils.formatDate (new Date ()); import "./styles/global.css" ;
路径别名 @ :Vue 项目里 @ 通常配置为 src/ 目录,需要看 vite.config.js 里的 resolve.alias 配置。注意 @ 不是 JS 语法,是构建工具的约定。
TypeScript基础 什么是TypeScript TypeScript 是 JavaScript 的超集:JS 代码本身就是合法的 TS 代码 ,TS 只是给 JS 加上了静态类型系统。对 Java 开发者来说,这是整个前端技术栈里最亲切的一环——你终于能在编译期发现”这个字段可能为 null””这个参数传错了类型”。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ┌──────────────────────────────────────────────────────────────────┐ │ TypeScript 关键事实 │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ 1. TS ≠ 新语言,是JS + 类型注解 │ │ .ts / .vue 文件 → tsc或Vite编译 → .js 文件 → 浏览器执行 │ │ 浏览器不认识TS,就像JVM不认识Kotlin源码一样 │ │ │ │ 2. 类型只在编译期存在,运行时全部擦除(type erasure) │ │ const user: User = ... │ │ 编译后 → const user = ... (类型信息消失) │ │ ⚠️ 所以不能像Java反射那样在运行时拿到类型 │ │ 例外:enum / class / 装饰器 会生成真实运行时代码 │ │ │ │ 3. 结构化类型系统(鸭子类型),不是Java的标称类型 │ │ Java:必须 implements 声明的接口才算"是" │ │ TS:只要"形状"一致就兼容,不需要显式声明 │ │ │ │ 4. 类型错误不阻止运行 │ │ Java:编译不通过 → 没有class文件 → 无法运行 │ │ TS:可以配置忽略错误照样产出JS(Vite甚至不做类型检查!) │ │ 这就是为什么需要 CI 里单独跑 vue-tsc 做类型检查 │ │ │ └──────────────────────────────────────────────────────────────────┘
类型注解 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 const name : string = "张三" ;const age : number = 26 ;const isVip : boolean = true ;const tags : string [] = ["a" , "b" ];const scores : Record <string , number > = { math : 95 };const count = 1 ; const list = [1 , 2 , 3 ]; function add (a : number , b : number ): number { return a + b; } function greet (name : string , greeting = "你好" ): string { return `${greeting} , ${name} ` ; } const double = (x : number ): number => x * 2 ;function createUser (name : string , age ?: number ) { } function createUser2 (name : string , age : number = 18 ) {}
类型对照表 :
Java
TypeScript
说明
String
string
小写,字面量类型
int / long / double
number
只有一个number类型
boolean
boolean
null
null / undefined
两个空值,都可能出现在类型里
Object
object / unknown
unknown 是类型安全的”任意值”
List<String>
string[] 或 Array<string>
Map<K,V>
Map<K,V> 或 Record<string, V>
Map 是运行时结构;Record 只是对象字面量的类型,键只能是 string/number/symbol
T 泛型
<T>
语法几乎一致
void
void
也有 never 表示”永不返回”
Integer(可空)
number | null
TS必须显式处理空值
Enum
enum / 字面量联合类型
社区更推荐后者
@Nullable
| undefined
strictNullChecks 下必检
interface 与 type:定义数据结构 这是日常写得最多的东西——对应你在后端写的 DTO / VO 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 interface UserVO { id : number ; username : string ; nickname ?: string ; readonly email : string ; vip ?: boolean ; } const user : UserVO = { id : 1 , username : "admin" , email : "admin@example.com" , }; interface AdminVO extends UserVO { level : number ; } interface UserVO { avatar ?: string ; }
1 2 3 4 5 6 7 8 9 type ID = string | number ; type Status = "loading" | "success" | "error" ; type UserWithRole = UserVO & { role : string };
联合类型、字面量类型(Java没有的概念) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 function format (value : string | number ): string { return String (value); } let nickname : string | null = null ;type Status = "loading" | "success" | "error" ;let status : Status = "loading" ;function handle (status : Status ) { switch (status) { case "loading" : return "加载中" ; case "success" : return "成功" ; case "error" : return "失败" ; } } interface ApiResponse <T> { code : number ; message : string ; data : T; }
泛型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 function getFirst<T>(list : T[]): T { return list[0 ]; } const first = getFirst ([1 , 2 , 3 ]); const firstStr = getFirst (["a" , "b" ]); interface HasId { id : number ; } function findById<T extends HasId >(list : T[], id : number ): T | undefined { return list.find ((item ) => item.id === id); } interface Page <T = unknown > { list : T[]; total : number ; page : number ; size : number ; } const userPage : Page <UserVO > = { list : [], total : 0 , page : 1 , size : 10 };interface ApiResponse <T> { code : number ; message : string ; data : T; } type UserPageResponse = ApiResponse <Page <UserVO >>;
类型收窄(类型守卫) Java 有 instanceof 做类型判断,TS 在这方面做得更细,且是编译期检查 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 function format (value : string | number ) { if (typeof value === "number" ) { return value.toFixed (2 ); } return value.trim (); } function handleError (error : unknown ) { if (error instanceof Error ) { console .log (error.message ); } else { console .log (String (error)); } } interface Cat { meow : () => void }interface Dog { bark : () => void }function speak (animal : Cat | Dog ) { if ("meow" in animal) { animal.meow (); } else { animal.bark (); } } type RequestState = | { status : "idle" } | { status : "loading" } | { status : "success" ; data : UserVO [] } | { status : "error" ; message : string }; function render (state : RequestState ) { switch (state.status ) { case "idle" : return "等待中" ; case "loading" : return "加载中" ; case "success" : return state.data .length ; case "error" : return state.message ; } }
any、unknown、never 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 let a : any = 1 ;a.foo .bar .baz (); let b : unknown = getFromServer ();if (typeof b === "string" ) { b.length ; } type Status = "loading" | "success" | "error" ;function assertNever (value : never ): never { throw new Error (`遗漏的分支: ${value} ` ); } const el = document .querySelector ("#app" ) as HTMLDivElement ;const el2 = document .querySelector ("#app" );if (el2 instanceof HTMLDivElement ) { el2.innerHTML = "" ; }
工具类型(高频使用) 对应 Java 里 Lombok 的 @Builder、MapStruct 的转换——但 TS 是从已有类型派生出新类型 ,不需要写模板代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 interface UserVO { id : number ; username : string ; email : string ; nickname : string ; createdAt : string ; } type UserUpdateDTO = Partial <UserVO >;type UserRequired = Required <UserVO >;type UserBrief = Pick <UserVO , "id" | "username" >;type UserCreateDTO = Omit <UserVO , "id" | "createdAt" >;type UserMap = Record <string , UserVO >;type ReadonlyUser = Readonly <UserVO >;async function fetchUser ( ): Promise <UserVO > { }type FetchUserResult = Awaited <ReturnType <typeof fetchUser>>; type LoginForm = Pick <UserVO , "username" > & { password : string };
与后端交互:类型定义示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 export interface ApiResponse <T = unknown > { code : number ; message : string ; data : T; } export interface PageResult <T> { list : T[]; total : number ; page : number ; size : number ; } export interface UserVO { id : number ; username : string ; nickname : string ; email : string ; } export interface LoginRequest { username : string ; password : string ; } export interface LoginResponse { token : string ; userInfo : UserVO ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import request from "./request" ;import type { LoginRequest , LoginResponse , UserVO } from "@/types/api" ;export function login (data : LoginRequest ): Promise <LoginResponse > { return request.post ("/login" , data); } export function getProfile ( ): Promise <UserVO > { return request.get ("/profile" ); }
与Vue结合 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 <!-- ============ 只是把 script 标签加上 lang="ts" ============ --> <template> <div>{{ displayName }}</div> <UserCard v-for="user in userList" :key="user.id" :user="user" /> </template> <script setup lang="ts"> import { ref, reactive, computed } from "vue"; import type { UserVO } from "@/types/api"; // ref 用泛型指定内部类型 const userList = ref<UserVO[]>([]); // 类型:Ref<UserVO[]> const loading = ref<boolean>(false); const keyword = ref(""); // 推断为 Ref<string> // ⚠️ 没有初始值的对象要显式声明,否则是 Ref<null> const userInfo = ref<UserVO | null>(null); // 复杂表单用接口 + reactive interface LoginForm { username: string; password: string; remember: boolean; } const form = reactive<LoginForm>({ username: "", password: "", remember: false, }); // computed 的返回类型会自动推断,无需手写 const displayName = computed(() => userInfo.value?.nickname ?? "未登录"); // ============ defineProps:用泛型声明(Vue3.3+推荐写法)============ // 写法1:泛型(类型来自接口,最简洁) interface Props { user: UserVO; showEmail?: boolean; } const props = defineProps<Props>(); // 带默认值用 withDefaults const props2 = withDefaults(defineProps<Props>(), { showEmail: false, }); // 写法2:运行时声明(旧写法,仍兼容,能同时做运行时校验) // const props = defineProps({ // user: { type: Object as PropType<UserVO>, required: true }, // }); // ============ defineEmits:泛型声明事件签名 ============ const emit = defineEmits<{ (e: "detail", id: number): void; (e: "delete", id: number): void; }>(); // 调用时参数类型会被检查 emit("detail", 1); // emit("detail", "1"); // ❌ 类型不匹配,编译报错 </script>
Vue3 + TS 的常见坑 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <script setup lang="ts"> // defineProps 的解构:Vue3.5+ 起解构仍保持响应性(编译器会自动转换) // 若项目用 Vue3.5 之前的版本,解构会丢失响应性,需改用 props.user const { user } = defineProps<Props>(); // ✅ 3.5 之前的写法:在 <script> 中访问 props 必须用 props.user // 模板中可以直接写 user // ❌ ref 声明的对象,忘了 .value const userInfo = ref<UserVO | null>(null); // userInfo.username = "x"; // ❌ 类型报错,因为 userInfo 是 Ref userInfo.value!.username = "x"; // ✅ // 也可以用泛型参数直接传 Ref 场景的安全写法 // ❗ 非空断言 ! 要慎用,它会跳过null检查 </script>
tsconfig.json(对应后端的编译配置) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 { "compilerOptions" : { "target" : "ES2020" , "module" : "ESNext" , "moduleResolution" : "bundler" , "strict" : true , "strictNullChecks" : true , "noImplicitAny" : true , "noUnusedLocals" : true , "noUnusedParameters" : true , "paths" : { "@/*" : [ "./src/*" ] } , "skipLibCheck" : true , "types" : [ "vite/client" ] } , "include" : [ "src/**/*.ts" , "src/**/*.d.ts" , "src/**/*.vue" ] }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ┌──────────────────────────────────────────────────────────────────┐ │ strict: true 到底开了什么 │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ • strictNullChecks null/undefined必须显式处理(最重要) │ │ • noImplicitAny 隐式any报错,逼你写类型 │ │ • strictFunctionTypes 函数参数逆变检查 │ │ • strictPropertyInitialization 类字段必须初始化 │ │ • noImplicitThis this必须明确类型 │ │ │ │ 为什么重要:类比Java里"打开所有编译警告"—— │ │ 一开始会觉得处处受限,但它挡住了绝大部分运行时NullPointerException│ │ 新项目一律 strict: true,老项目可以逐项打开。 │ │ │ │ ⚠️ Vite 默认不做类型检查(为了快),必须靠: │ │ • 编辑器(Volar插件)实时提示 │ │ • 命令行 vue-tsc --noEmit 做全量检查(放进CI) │ │ │ └──────────────────────────────────────────────────────────────────┘
给Java选手的TypeScript心法 :
类型不匹配在写代码时 就报错,不用等到运行——这是你最熟悉的部分,享受它
但类型是擦除 的,运行时没有类型信息,不能用反射;as 只是承诺,不是转换
strictNullChecks 相当于强制的 Optional,一开始会烦,习惯后能消灭大量空指针问题
类型定义不要追求”完备”,从核心的接口出入参开始标类型,其余靠推断即可
any 是逃生舱不是常规武器,用得多了等于白上TS
Vue3框架基础 什么是Vue Vue 是一个声明式 的前端框架。核心区别在于:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ┌──────────────────────────────────────────────────────────────────┐ │ 命令式 vs 声明式(心智模型转变) │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ 命令式(原生JS / jQuery)—— 你告诉浏览器"怎么做" │ │ ────────────────────────────────────────────────────────────── │ │ if (user) { │ │ el.textContent = user.name; │ │ } else { │ │ el.textContent = ""; │ │ } │ │ │ │ 声明式(Vue)—— 你告诉浏览器"数据和界面的关系" │ │ ────────────────────────────────────────────────────────────── │ │ <span>{{ user?.name }}</span> │ │ │ │ 数据变化 → Vue自动重新渲染受影响的DOM │ │ │ │ 类比:你写 MyBatis 的 SQL 映射,而不是手动遍历ResultSet │ │ │ └──────────────────────────────────────────────────────────────────┘
一个组件长什么样(SFC) Vue 的一个 .vue 文件就是一个组件,包含三块(单文件组件 SFC):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <!-- src/components/UserCard.vue --> <template> <!-- 1. 模板:描述界面结构(类似Thymeleaf,但要配合响应式数据) --> <div class="user-card"> <h3>{{ user.name }}</h3> <p>{{ user.email }}</p> <button @click="handleClick">查看详情</button> </div> </template> <script setup> // 2. 逻辑:声明数据、函数、引入子组件 // 注意:defineProps / defineEmits 是编译宏,无需 import const props = defineProps({ user: { type: Object, required: true }, }); const emit = defineEmits(["detail"]); function handleClick() { emit("detail", props.user.id); } </script> <style scoped> /* 3. 样式:scoped表示只作用于当前组件,不污染全局 */ .user-card { border: 1px solid #eee; padding: 16px; border-radius: 8px; } </style>
和 SpringBoot 的分层对应关系 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ┌──────────────────────────────────────────────────────────────────┐ │ Vue组件 vs Spring分层 │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ SpringBoot Vue3 │ │ ───────────────────────────────────────────────────────────── │ │ @RestController 组件(.vue文件) │ │ DTO / VO 组件内部响应式数据 ref/reactive │ │ @Service composables(useXxx函数) │ │ @Repository/Mapper api层(axios封装) │ │ @Autowired注入 import后直接使用 │ │ @ConfigurationProperties Pinia store / provide │ │ @Validated 表单校验规则 + 后端校验 │ │ │ │ 注意:组件既是"接口层"也是"展示层",没有后端那么清晰的分层, │ │ 但复杂逻辑应当抽到 composables 里,别都堆在组件里。 │ │ │ └──────────────────────────────────────────────────────────────────┘
响应式数据:ref 与 reactive 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <script setup> import { ref, reactive } from "vue"; // ============ ref:包装任意类型(最常用)============ const count = ref(0); // 基本类型 const user = ref(null); // 对象 // 在 <script> 中访问必须加 .value count.value = 1; user.value = { name: "张三" }; console.log(count.value); // 1 // 在 <template> 中自动解包,不用写 .value // {{ count }} 即可 // ============ reactive:只能包装对象/数组 ============ const form = reactive({ username: "", password: "", remember: false, }); // reactive 不需要 .value,直接改属性 form.username = "admin"; // 等价于下面这种"用 ref 包对象"的写法(两者都可以,推荐统一用 ref) // const form = ref({ username: "" }); // form.value.username = "admin"; </script>
为什么需要响应式? 在原生 JS 里改了变量,DOM 不会自动更新;在 Vue 里改了 ref,用到它的模板会自动重渲染。这是框架的核心价值。
⚠️ 常见的响应式丢失 :
1 2 3 4 5 6 const { username } = form;import { toRefs } from "vue" ;const { username } = toRefs (form);
模板语法:插值与指令 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 <template> <!-- ============ 1. 插值:{{ 表达式 }} ============ --> <p>你好,{{ username }}</p> <p>{{ age + 1 }}</p> <p>{{ isVip ? "会员" : "普通用户" }}</p> <!-- 插值会自动转义HTML(防XSS),需要渲染HTML用 v-html(慎用) --> <!-- ============ 2. v-bind:绑定属性(简写 : )============ --> <img :src="avatarUrl" :alt="username" /> <div :class="{ active: isActive, disabled: isDisabled }"></div> <div :class="['base', isActive ? 'on' : 'off']"></div> <div :style="{ color: textColor, fontSize: fontSize + 'px' }"></div> <!-- :key 是列表渲染的必需项,见下文 --> <!-- ============ 3. v-on:绑定事件(简写 @ )============ --> <button @click="handleLogin">登录</button> <button @click="handleDelete(user.id)">删除</button> <button @click="count++">加一</button> <input @keyup.enter="submit" /> <form @submit.prevent="submit"> <!-- .prevent 阻止默认提交刷新 --> <!-- @click.stop 阻止冒泡,@click.once 只触发一次 --> </form> <!-- ============ 4. v-model:双向绑定(表单核心)============ --> <input v-model="form.username" placeholder="用户名" /> <input v-model="form.password" type="password" /> <input v-model.number="form.age" type="number" /> <!-- .number 转数字 --> <input v-model.trim="form.email" /> <!-- .trim 去首尾空格 --> <input v-model.lazy="form.remark" /> <!-- .lazy 失焦才同步 --> <input type="checkbox" v-model="form.remember" /> <!-- 原理:v-model 是 :value + @input 的语法糖 --> <!-- ============ 5. v-if / v-show:条件渲染 ============ --> <div v-if="status === 'loading'">加载中...</div> <div v-else-if="status === 'error'">加载失败</div> <div v-else>{{ data }}</div> <!-- 频繁切换的显隐用 v-show(只是 display:none,不销毁DOM) --> <div v-show="isOpen">抽屉内容</div> <!-- v-if 会真正创建/销毁DOM,适合条件不常变的场景 --> <!-- ============ 6. v-for:列表渲染 ============ --> <ul> <li v-for="item in userList" :key="item.id"> {{ item.name }} </li> </ul> <li v-for="(item, index) in userList" :key="item.id"> {{ index }} - {{ item.name }} </li> <li v-for="(value, key) in userObject" :key="key">{{ key }}: {{ value }}</li> <!-- v-for 和 v-if 不要写在同一个元素上,v-if 优先级更高会导致意外行为 --> </template>
关于 :key :Vue 靠 key 判断”哪个元素是哪个”。key 必须唯一且稳定,不要用数组下标 ——删除中间元素时会导致渲染错乱。
1 2 3 4 5 <!-- ❌ 用index做key,删除第一项后所有项都会重新渲染 --> <li v-for="(item, index) in list" :key="index"> <!-- ✅ 用业务唯一ID --> <li v-for="item in list" :key="item.id">
computed 与 watch 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 <script setup> import { ref, computed, watch, watchEffect } from "vue"; const firstName = ref("三"); const lastName = ref("张"); const userList = ref([]); // ============ computed:派生数据,有缓存(推荐优先使用)============ // 类似Java的 getter,但会缓存:依赖不变就不会重新计算 const fullName = computed(() => lastName.value + firstName.value); const activeCount = computed(() => userList.value.filter((u) => u.status === 1).length ); // 可写计算属性(少见,需要时用) const count = ref(1); const doubleCount = computed({ get: () => count.value * 2, set: (val) => { count.value = val / 2; }, }); // ============ watch:监听变化执行副作用 ============ // 类似Java的监听器/事件订阅,用于发请求、操作DOM、写日志 // 监听单个来源 const keyword = ref(""); watch(keyword, (newVal, oldVal) => { console.log(`从 ${oldVal} 变成 ${newVal}`); }); // 监听多个来源 watch([firstName, lastName], ([newFirst, newLast]) => { console.log("姓名变了", newFirst, newLast); }); // 监听对象的某个字段(需要用函数形式指定) const form = ref({ username: "", password: "" }); watch( () => form.value.username, (newVal) => { // 可用于搜索联想 } ); // 深度监听整个对象(性能开销较大,慎用) watch(form, () => {}, { deep: true }); // 立即执行一次(默认只在变化时触发) watch(keyword, () => {}, { immediate: true }); // 防抖搜索(前端高频场景) let timer = null; watch(keyword, (val) => { clearTimeout(timer); timer = setTimeout(() => { search(val); }, 300); }); // ============ watchEffect:自动收集依赖 ============ // 不需要指定监听源,用到了什么就监听什么 watchEffect(() => { console.log("username是", keyword.value); }); </script>
computed vs watch 怎么选 :
场景
用什么
由现有数据”算”出新数据(如总价、过滤后列表)
computed
数据变化时要”做一件事”(发请求、存缓存、改DOM)
watch
想在模板里直接展示派生结果
computed
铁律 :不要在 computed 里发请求或修改其他状态,那是 watch 的职责。
生命周期 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ┌──────────────────────────────────────────────────────────────────┐ │ 组件生命周期(组合式API) │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ 创建 setup() 执行 │ │ │ │ │ ├─ onBeforeMount 挂载前:可以准备数据 │ │ │ │ │ 挂载 ├─ onMounted 已挂载:DOM可用,可发请求/初始化图表 │ │ │ │ │ ├─ ← 数据变化,触发更新 → │ │ ├─ onBeforeUpdate 更新前 │ │ └─ onUpdated 更新后(DOM已同步) │ │ │ │ ├─ onBeforeUnmount 卸载前:清理定时器、取消请求 │ │ │ │ 卸载 └─ onUnmounted 已卸载:组件销毁 │ │ │ │ 对应概念:类似 Android 的 onCreate/onDestroy、 │ │ Servlet 的 init/destroy。 │ │ │ └──────────────────────────────────────────────────────────────────┘
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <script setup> import { onMounted, onUnmounted, ref } from "vue"; const timer = ref(null); onMounted(() => { // 组件挂载完成后执行:此时可以安全地发请求 loadData(); timer.value = setInterval(() => { console.log("轮询中"); }, 5000); }); onUnmounted(() => { // 清理工作,防止内存泄漏 clearInterval(timer.value); }); // ⚠️ onMounted 里写 async 回调要小心:Vue 不会等待 await, // 组件卸载后 await 后面的代码仍会执行(可能去操作已销毁的组件) onMounted(async () => { const data = await loadData(); }); </script>
组件通信:props 与 emit 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <!-- ============ 父组件:传递数据、监听事件 ============ --> <!-- ParentView.vue --> <template> <h2>用户列表</h2> <UserCard v-for="user in userList" :key="user.id" :user="user" :show-email="true" @detail="handleDetail" @delete="handleDelete" /> </template> <script setup> import { ref } from "vue"; import UserCard from "@/components/UserCard.vue"; const userList = ref([]); function handleDetail(id) { console.log("父组件收到子组件事件:", id); } function handleDelete(id) { userList.value = userList.value.filter((u) => u.id !== id); } </script>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <!-- ============ 子组件:接收props、抛出事件 ============ --> <!-- UserCard.vue --> <template> <div class="user-card"> <h3>{{ user.name }}</h3> <!-- props是只读的,子组件不能直接改 --> <p v-if="showEmail">{{ user.email }}</p> <button @click="$emit('detail', user.id)">详情</button> <button @click="emit('delete', user.id)">删除</button> </div> </template> <script setup> // defineProps 声明接收的属性(编译宏,无需import) const props = defineProps({ user: { type: Object, required: true, }, showEmail: { type: Boolean, default: false, }, }); // defineEmits 声明会抛出的事件 const emit = defineEmits(["detail", "delete"]); // 注意:不要在子组件里直接修改props.user // 需要修改时,应emit事件让父组件改("数据由谁持有,谁负责修改") </script>
props 命名规则 :camelCase 传参(:show-email)对应子组件中的 showEmail(模板里写 kebab-case,JS里写 camelCase)。
其他通信方式 :
插槽:让组件更灵活 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <!-- 布局组件:预留位置给使用者填充 --> <!-- CardLayout.vue --> <template> <div class="card"> <div class="header"> <slot name="header">默认标题</slot> <!-- 具名插槽,可给默认内容 --> </div> <div class="body"> <slot></slot> <!-- 默认插槽 --> </div> </div> </template> <!-- 使用 --> <CardLayout> <template #header> <h3>用户信息</h3> </template> 这里的内容会放进默认插槽 </CardLayout>
路由:vue-router 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 import { createRouter, createWebHistory } from "vue-router" ;const routes = [ { path : "/" , redirect : "/login" }, { path : "/login" , name : "login" , component : () => import ("@/views/LoginView.vue" ), meta : { requiresAuth : false , title : "登录" }, }, { path : "/home" , name : "home" , component : () => import ("@/views/HomeView.vue" ), meta : { requiresAuth : true , title : "首页" }, }, { path : "/user/:id" , name : "userDetail" , component : () => import ("@/views/UserDetailView.vue" ), props : true , }, { path : "/admin" , component : () => import ("@/views/AdminLayout.vue" ), children : [ { path : "users" , component : () => import ("@/views/AdminUsers.vue" ) }, ], }, { path : "/:pathMatch(.*)*" , component : () => import ("@/views/NotFoundView.vue" ), }, ]; const router = createRouter ({ history : createWebHistory (), routes, }); router.beforeEach ((to, from , next ) => { const token = localStorage .getItem ("token" ); if (to.meta .requiresAuth && !token) { next ({ name : "login" , query : { redirect : to.fullPath } }); return ; } next (); }); router.afterEach ((to ) => { document .title = to.meta .title ? `${to.meta.title} - 我的应用` : "我的应用" ; }); export default router;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <!-- ============ 在组件中使用路由 ============ --> <template> <!-- 声明式跳转 --> <router-link to="/home">去首页</router-link> <router-link :to="{ name: 'userDetail', params: { id: 1 } }">用户详情</router-link> <!-- 加载中显示的组件(配合懒加载) --> <router-view /> </template> <script setup> import { useRouter, useRoute } from "vue-router"; const router = useRouter(); // 编程式导航 const route = useRoute(); // 当前路由信息(只读) // 获取路由参数(对应后端 @PathVariable / @RequestParam) console.log(route.params.id); // /user/:id console.log(route.query.page); // ?page=1 console.log(route.path); // /user/1 console.log(route.name); // userDetail console.log(route.meta.title); // 路由元信息 // 跳转方式 router.push("/home"); router.push({ name: "userDetail", params: { id: 2 } }); router.push({ path: "/search", query: { keyword: "vue" } }); router.replace("/home"); // 不留下历史记录 router.back(); // 后退 </script>
⚠️ History 模式需要服务端配合 :部署时 Nginx 必须把所有找不到的路径回退到 index.html,否则直接访问 /home 会 404。
1 2 3 location / { try_files $uri $uri / /index.html; }
HTTP请求:axios 封装 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 import axios from "axios" ;const request = axios.create ({ baseURL : import .meta .env .VITE_API_BASE_URL || "/api" , timeout : 10000 , }); request.interceptors .request .use ( (config ) => { const token = localStorage .getItem ("token" ); if (token) { config.headers .Authorization = `Bearer ${token} ` ; } return config; }, (error ) => Promise .reject (error) ); request.interceptors .response .use ( (response ) => { const res = response.data ; if (res.code !== 200 ) { console .error ("业务错误:" , res.message ); return Promise .reject (new Error (res.message || "请求失败" )); } return res.data ; }, (error ) => { if (error.response ) { const status = error.response .status ; if (status === 401 ) { localStorage .removeItem ("token" ); window .location .href = "/login" ; } else if (status === 403 ) { console .error ("无权限" ); } else { console .error ("请求失败:" , status); } } return Promise .reject (error); } ); export default request;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import request from "./request" ;export function login (data ) { return request.post ("/login" , data); } export function register (data ) { return request.post ("/register" , data); } export function getProfile ( ) { return request.get ("/profile" ); } export function getUserById (id ) { return request.get (`/users/${id} ` ); } export function getUsers (params ) { return request.get ("/users" , { params }); } export function updateUser (id, data ) { return request.put (`/users/${id} ` , data); } export function deleteUser (id ) { return request.delete (`/users/${id} ` ); }
环境变量 (对应 application.yml 的多环境配置):
1 2 3 4 5 VITE_API_BASE_URL=http://localhost:8080/api VITE_API_BASE_URL=/api
1 2 3 4 const baseUrl = import .meta .env .VITE_API_BASE_URL ;
全局状态:Pinia 多个页面/组件共享的数据(如登录用户信息)用 Pinia 管理,类似后端的 Session 或全局缓存。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 import { defineStore } from "pinia" ;import { ref, computed } from "vue" ;import { login as loginApi, getProfile } from "@/api/user" ;export const useUserStore = defineStore ("user" , () => { const token = ref (localStorage .getItem ("token" ) || "" ); const userInfo = ref (null ); const isLoggedIn = computed (() => !!token.value ); const displayName = computed ( () => userInfo.value ?.nickname || userInfo.value ?.username || "未登录" ); async function login (form ) { const data = await loginApi (form); token.value = data.token ; userInfo.value = data.userInfo ; localStorage .setItem ("token" , data.token ); return data; } async function fetchProfile ( ) { userInfo.value = await getProfile (); } function logout ( ) { token.value = "" ; userInfo.value = null ; localStorage .removeItem ("token" ); } return { token, userInfo, isLoggedIn, displayName, login, fetchProfile, logout }; });
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <!-- ============ 在组件中使用 ============ --> <script setup> import { storeToRefs } from "pinia"; import { useUserStore } from "@/stores/user"; const userStore = useUserStore(); // ✅ 用 storeToRefs 解构可以保持响应式 const { token, userInfo, isLoggedIn } = storeToRefs(userStore); // ⚠️ action可以直接解构,但state必须用storeToRefs const { login, logout } = userStore; </script> <template> <span v-if="isLoggedIn">{{ userInfo?.nickname }}</span> <button v-else @click="login({ username: 'admin', password: '123456' })">登录</button> </template>
用户登录Demo完整示例 项目结构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 user-login-web/ ├── index.html ├── package.json ├── vite.config.js ├── .env.development └── src/ ├── main.js ├── App.vue ├── assets/ │ └── main.css ├── router/ │ └── index.js ├── stores/ │ └── user.js ├── api/ │ ├── request.js │ └── user.js ├── views/ │ ├── LoginView.vue │ └── HomeView.vue └── components/ └── MessageToast.vue
配置文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import { fileURLToPath, URL } from "node:url" ;import { defineConfig } from "vite" ;import vue from "@vitejs/plugin-vue" ;export default defineConfig ({ plugins : [vue ()], resolve : { alias : { "@" : fileURLToPath (new URL ("./src" , import .meta .url )), }, }, server : { port : 5173 , proxy : { "/api" : { target : "http://localhost:8080" , changeOrigin : true , }, }, }, });
1 2 3 VITE_API_BASE_URL=/api
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <!DOCTYPE html > <html lang ="zh-CN" > <head > <meta charset ="UTF-8" /> <meta name ="viewport" content ="width=device-width, initial-scale=1.0" /> <title > 用户登录Demo</title > </head > <body > <div id ="app" > </div > <script type ="module" src ="/src/main.js" > </script > </body > </html >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import { createApp } from "vue" ;import { createPinia } from "pinia" ;import App from "./App.vue" ;import router from "./router" ;import "./assets/main.css" ;const app = createApp (App );app.use (createPinia ()); app.use (router); app.mount ("#app" );
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 * { box-sizing : border-box; } body { margin : 0 ; font-family : -apple-system, "PingFang SC" , "Microsoft YaHei" , sans-serif; background : #f5f6f8 ; color : #333 ; } button { cursor : pointer; border : none; border-radius : 6px ; font-size : 14px ; transition : all 0.2s ease; } button :disabled { cursor : not-allowed; opacity : 0.6 ; } input { outline : none; }
根组件 1 2 3 4 5 <!-- ============ src/App.vue ============ --> <template> <!-- router-view 是路由出口:当前URL匹配到的组件渲染在这里 --> <router-view /> </template>
请求封装与接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import axios from "axios" ;const request = axios.create ({ baseURL : import .meta .env .VITE_API_BASE_URL , timeout : 10000 , }); request.interceptors .request .use ((config ) => { const token = localStorage .getItem ("token" ); if (token) { config.headers .Authorization = `Bearer ${token} ` ; } return config; }); request.interceptors .response .use ( (response ) => { const res = response.data ; if (res.code !== 200 ) { return Promise .reject (new Error (res.message || "请求失败" )); } return res.data ; }, (error ) => { if (error.response ?.status === 401 ) { localStorage .removeItem ("token" ); window .location .href = "/login" ; } return Promise .reject (error); } ); export default request;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import request from "./request" ;export function login (data ) { return request.post ("/login" , data); } export function register (data ) { return request.post ("/register" , data); } export function getProfile ( ) { return request.get ("/profile" ); }
Pinia Store 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import { defineStore } from "pinia" ;import { ref, computed } from "vue" ;import { login as loginApi, getProfile } from "@/api/user" ;export const useUserStore = defineStore ("user" , () => { const token = ref (localStorage .getItem ("token" ) || "" ); const userInfo = ref (null ); const isLoggedIn = computed (() => !!token.value ); const displayName = computed (() => userInfo.value ?.nickname || "未登录" ); async function login (form ) { const data = await loginApi (form); token.value = data.token ; userInfo.value = data.userInfo ; localStorage .setItem ("token" , data.token ); } async function fetchProfile ( ) { userInfo.value = await getProfile (); } function logout ( ) { token.value = "" ; userInfo.value = null ; localStorage .removeItem ("token" ); } return { token, userInfo, isLoggedIn, displayName, login, fetchProfile, logout }; });
登录页面 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 <!-- ============ src/views/LoginView.vue ============ --> <template> <div class="login-page"> <form class="login-box" @submit.prevent="handleSubmit"> <h1 class="title">用户登录</h1> <div class="field"> <label for="username">用户名</label> <input id="username" v-model.trim="form.username" type="text" placeholder="请输入用户名" :disabled="loading" /> <!-- v-if 控制错误提示,只有校验失败才渲染 --> <p v-if="errors.username" class="error">{{ errors.username }}</p> </div> <div class="field"> <label for="password">密码</label> <input id="password" v-model="form.password" type="password" placeholder="请输入密码" :disabled="loading" /> <p v-if="errors.password" class="error">{{ errors.password }}</p> </div> <label class="remember"> <input v-model="form.remember" type="checkbox" /> 记住我 </label> <!-- :disabled 绑定 loading,防止重复提交 --> <button type="submit" :disabled="loading"> {{ loading ? "登录中..." : "登 录" }} </button> <p v-if="errorMessage" class="error server-error">{{ errorMessage }}</p> </form> </div> </template> <script setup> import { ref, reactive, computed } from "vue"; import { useRouter, useRoute } from "vue-router"; import { useUserStore } from "@/stores/user"; const router = useRouter(); const route = useRoute(); const userStore = useUserStore(); // 表单数据 const form = reactive({ username: "", password: "", remember: false, }); const loading = ref(false); // 提交中 const errorMessage = ref(""); // 服务端返回的错误 // 前端表单校验(呼应后端的 @Validated,但前端校验只为体验,安全靠后端) const errors = computed(() => { const result = {}; if (form.username && form.username.length < 3) { result.username = "用户名至少3个字符"; } if (form.password && form.password.length < 6) { result.password = "密码至少6个字符"; } return result; }); const canSubmit = computed( () => form.username.length >= 3 && form.password.length >= 6 ); // 回车提交由 form 的 @submit.prevent 统一处理,这里只需防重复触发 async function handleSubmit() { if (loading.value) return; errorMessage.value = ""; if (!canSubmit.value) { errorMessage.value = "请检查输入内容"; return; } loading.value = true; try { await userStore.login(form); // 登录成功,跳转到重定向目标或首页 const redirect = route.query.redirect || "/home"; router.replace(redirect); } catch (error) { // 后端返回的都是用户可读的提示,直接展示 errorMessage.value = error.message || "登录失败,请稍后重试"; } finally { // 无论成功失败都恢复按钮状态 loading.value = false; } } </script> <style scoped> .login-page { display: flex; justify-content: center; align-items: center; min-height: 100vh; } .login-box { width: 360px; padding: 32px; background: #fff; border-radius: 12px; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08); } .title { margin: 0 0 24px; font-size: 22px; text-align: center; } /* 注意:scoped下不能靠标签名影响子组件的深层结构,但普通元素没问题 */ .field { margin-bottom: 16px; display: flex; flex-direction: column; } .field label { margin-bottom: 6px; font-size: 13px; color: #666; } .field input { height: 40px; padding: 0 12px; border: 1px solid #dcdfe6; border-radius: 6px; font-size: 14px; } .field input:focus { border-color: #1677ff; } .remember { display: flex; align-items: center; gap: 6px; margin-bottom: 20px; font-size: 13px; color: #666; } button[type="submit"] { width: 100%; height: 42px; background: #1677ff; color: #fff; font-size: 15px; } button[type="submit"]:hover:not(:disabled) { background: #4096ff; } .error { margin: 6px 0 0; font-size: 12px; color: #f56c6c; } .server-error { text-align: center; margin-top: 12px; } </style>
首页 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 <!-- ============ src/views/HomeView.vue ============ --> <template> <div class="page"> <header class="navbar"> <h1>首页</h1> <div class="user-area"> <span>{{ userStore.displayName }}</span> <button class="logout" @click="handleLogout">退出登录</button> </div> </header> <main class="main"> <p v-if="loading">加载中...</p> <template v-else-if="userInfo"> <p>ID:{{ userInfo.id }}</p> <p>用户名:{{ userInfo.username }}</p> <p>昵称:{{ userInfo.nickname }}</p> <p>邮箱:{{ userInfo.email }}</p> </template> </main> </div> </template> <script setup> import { ref, onMounted } from "vue"; import { storeToRefs } from "pinia"; import { useRouter } from "vue-router"; import { useUserStore } from "@/stores/user"; const router = useRouter(); const userStore = useUserStore(); const { userInfo } = storeToRefs(userStore); const loading = ref(false); // 组件挂载后拉取用户信息(类似 @PostConstruct) onMounted(async () => { loading.value = true; try { await userStore.fetchProfile(); } catch (error) { console.error("获取用户信息失败", error); } finally { loading.value = false; } }); function handleLogout() { userStore.logout(); router.replace("/login"); } </script> <style scoped> .page { min-height: 100vh; } .navbar { display: flex; justify-content: space-between; align-items: center; height: 60px; padding: 0 24px; background: #fff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06); } .navbar h1 { margin: 0; font-size: 18px; } .user-area { display: flex; align-items: center; gap: 12px; } .logout { padding: 6px 14px; background: #f2f3f5; color: #333; } .main { max-width: 720px; margin: 24px auto; padding: 24px; background: #fff; border-radius: 12px; } </style>
运行与测试 1 2 3 4 5 6 7 8 9 10 11 12 npm install npm run dev npm run build npm run preview
浏览器调试必备 :
工具
用途
F12 / Ctrl+Shift+I
打开开发者工具
Elements 面板
查看/临时修改DOM和CSS,定位样式问题
Console 面板
看 console.log、JS报错,直接执行JS
Network 面板
看每个请求的URL、Header、请求体、响应、耗时
Application 面板
查看 localStorage / Cookie / Session Storage
Vue Devtools(浏览器插件)
查看组件树、每个组件的响应式数据、Pinia状态
后端视角的排查思路 :接口报错先去 Network 面板看请求是否发出、URL是否正确、状态码和响应体是什么。前端99%的”没有数据”都能在 Network 面板找到答案——要么请求没发出去(前端逻辑问题),要么请求发出但返回错误(看状态码和后端日志)。
前后端联调常见问题 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 ┌──────────────────────────────────────────────────────────────────┐ │ 联调高频问题速查 │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ 1. 跨域(CORS) │ │ 现象:Console报 "has been blocked by CORS policy" │ │ 原因:浏览器同源策略,前端5173端口访问8080端口的接口 │ │ 方案A:开发环境用Vite server.proxy代理(推荐,本文Demo的方式) │ │ 方案B:后端加CORS配置 │ │ SpringBoot: @CrossOrigin 或 WebMvcConfigurer.addCorsMappings │ │ 方案C:生产环境用Nginx同域部署(前端静态资源+API同域名) │ │ 注意:CORS是浏览器行为,Postman不带Origin所以不受影响 │ │ │ │ 2. 401 未登录 / Token失效 │ │ 检查:Network的Request Headers里有没有 Authorization │ │ 检查:Token是否过期,localStorage里是否还存在 │ │ │ │ 3. 请求发出但参数为空 │ │ GET:参数放 params,被拼进URL → 后端用 @RequestParam │ │ POST:参数放 body(JSON) → 后端用 @RequestBody │ │ 两者混用是新手最常见的错误 │ │ │ │ 4. 响应数据结构对不上 │ │ 检查响应拦截器返回的是 res 还是 res.data │ │ 在 Network 面板对照后端真实返回结构 │ │ │ │ 5. 页面刷新后302到登录页 │ │ 原因:Token存在store(内存)里,刷新就丢了 │ │ 方案:持久化到 localStorage(本文Demo的做法) │ │ 更安全方案:HttpOnly Cookie + 后端会话 │ │ │ │ 6. 打包后部署到Nginx,刷新页面404 │ │ 原因:History模式路由,/home 在服务器上不存在 │ │ 方案:Nginx 配置 try_files $uri $uri/ /index.html; │ │ │ └──────────────────────────────────────────────────────────────────┘
安全注意事项 前后端分离后,安全责任有一部分转移到了前端,但核心安全永远在后端 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 const apiSecret = "sk-xxxxxxxx" ;const privateKey = "-----BEGIN PRIVATE KEY-----" ;await request.post ("/pay" , { orderId : 123 });import DOMPurify from "dompurify" ;const safeHtml = DOMPurify .sanitize (rawHtml);
Java与JavaScript/Vue对比速查表
场景
后端 Java
前端 JavaScript / Vue
变量声明
String s = "a";
const s = "a";
变量声明(带类型)
String s = "a";
const s: string = "a";
常量
final
const(引用不可变,对象内容可变)
只读字段
final 字段
readonly 修饰符
数据结构定义
class UserVO + Lombok
interface UserVO
可空类型
@Nullable / Optional<T>
T | null(strictNullChecks 强制处理)
枚举
enum Status
字面量联合 "a" | "b" | "c"
类型转换
(String) obj 运行时检查
as string 仅编译期承诺,运行时不检查
派生类型
手写 DTO / MapStruct
Partial<T> / Pick<T,K> / Omit<T,K>
类型生成
编译后保留(反射可用)
编译后擦除(不能反射)
字符串拼接
"a" + b
`a${b}`
相等判断
equals() / ==
===(慎用 ==)
空值
null
null / undefined,用 ?. ?? 兜底
函数
方法定义在类内
函数是一等公民,箭头函数 (x) => x*2
集合遍历
for (User u : list)
list.forEach(u => {}) / v-for
集合转换
stream().map().collect()
list.map() / .filter()
对象定义
class User {} + Lombok
对象字面量 {} / class
解构
无直接等价物
const { name } = user;
继承
extends
extends(但更推荐组合)
接口
interface
无(TypeScript提供)
异常处理
try-catch
try-catch(异步要配 async/await)
异步
CompletableFuture / 线程池
Promise / async-await(单线程事件循环)
并发等待全部
allOf().join()
await Promise.all([...])
模块
package + import
import / export
依赖管理
Maven pom.xml
npm package.json
依赖注入
Spring IoC(容器自动装配)
import 直接引入 / provide-inject
配置多环境
application-dev.yml
.env.development + import.meta.env
路由
@RequestMapping
vue-router 的 routes
拦截器
HandlerInterceptor
axios 拦截器 / 路由守卫
请求参数
@RequestParam
params → 拼在URL上
请求体
@RequestBody
data → JSON body
返回JSON
@RestController 自动序列化
axios 自动解析 response.data
模板渲染
Thymeleaf
Vue 的 <template>
全局状态
Session / 单例Bean
Pinia store
持久化
数据库
localStorage / sessionStorage / Cookie
单元测试
JUnit + Mockito
Vitest + Vue Test Utils
打包产物
jar / war
dist/ 下的静态文件
进阶学习路线 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 ┌──────────────────────────────────────────────────────────────────┐ │ 前端进阶学习路线 │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ 第一阶段:三件套打牢 │ │ ─────────────────────────────────────────────────────────────── │ │ • HTML语义化、表单、可访问性(a11y) │ │ • CSS:Flex/Grid布局、层叠与优先级、响应式、变量(--var) │ │ • JS:作用域与闭包、原型链、this指向、事件循环、Promise │ │ • 浏览器:渲染流程、重排重绘、缓存、跨域原理 │ │ │ │ 第二阶段:Vue深入 │ │ ─────────────────────────────────────────────────────────────── │ │ • 响应式原理:Proxy、依赖收集、effect调度 │ │ • 组件进阶:插槽、动态组件、异步组件、Teleport │ │ • 组合式函数:把复用逻辑抽成 useXxx │ │ • 性能优化:v-memo、shallowRef、虚拟列表、懒加载 │ │ • 状态管理:Pinia进阶(持久化、模块拆分) │ │ • Element Plus / Ant Design Vue 等UI组件库 │ │ │ │ 第三阶段:工程化 │ │ ─────────────────────────────────────────────────────────────── │ │ • TypeScript进阶:声明文件、类型体操、openapi自动生成接口类型 │ │ • vue-tsc + CI 做全量类型检查 │ │ • 构建工具:Vite原理、打包优化、代码分割、按需引入 │ │ • 代码规范:ESLint + Prettier + Husky │ │ • 测试:Vitest单元测试、Playwright/Cypress端到端 │ │ • 部署:Nginx配置、CDN、Docker、CI/CD │ │ │ │ 第四阶段:全栈与拓展 │ │ ─────────────────────────────────────────────────────────────── │ │ • SSR/SSG:Nuxt(Vue的服务端渲染框架,利于SEO和首屏) │ │ • 微前端:qiankun、Module Federation │ │ • 跨端:uni-app、Tauri、Electron │ │ • 可视化:ECharts、Three.js │ │ • Web性能:Core Web Vitals、Lighthouse优化 │ │ │ │ 推荐学习资源 │ │ ─────────────────────────────────────────────────────────────── │ │ • 官方文档:https://cn.vuejs.org/ │ │ • MDN:https://developer.mozilla.org/zh-CN/ │ │ • 路由:https://router.vuejs.org/zh/ │ │ • Pinia:https://pinia.vuejs.org/zh/ │ │ • Vite:https://cn.vitejs.dev/ │ │ • 现代JS教程:https://zh.javascript.info/ │ │ • 图解Flex:https://css-tricks.com/snippets/css/a-guide-to-flexbox/│ │ │ └──────────────────────────────────────────────────────────────────┘
总结 从Java后端转向前端,核心变化:
运行环境不同 :代码跑在用户的浏览器里,环境不可控、数据不可信、密钥藏不住
编程范式不同 :从”命令式地一步步改DOM”变成”声明式地描述数据与界面的关系”,由框架负责渲染
异步模型不同 :单线程事件循环,没有线程池,异步统一靠 Promise / async-await
类型系统不同 :JS是动态类型,编译期不查错;想要接近Java的类型安全需要引入TypeScript(好消息是TS的泛型、interface、工具类型几乎是Java的翻版)
工程链路不同 :npm 管依赖、Vite 管构建、产物是静态文件,直接丢给 Nginx 或 CDN 即可,不需要应用服务器
分层不会消失,只是换了名字 :Controller → 组件,Service → composable,Mapper → api,DTO → interface,编译期类型检查 → TypeScript
建议的学习路径:
先跑通本文的Demo,理解”数据变化 → 视图更新”的闭环
补扎实JS基础,特别是 异步(Promise/async-await) 和 数组方法(map/filter/reduce) ,这两块是读懂前端代码的入场券
掌握Vue的响应式(ref/reactive/computed/watch)和组件通信(props/emit),这是日常开发90%的工作
用浏览器开发者工具(尤其是Network面板)建立排查问题的直觉
尽早引入TypeScript :配好 strict: true 和编辑器的Volar插件,让编译期帮你抓空指针和字段拼写——这是前端里最接近写Java体验的部分
配套阅读:本文讲”怎么用”,进阶原理可看《前端面试八股文——必背要点与深度解析》,那篇讲”为什么”——涵盖 JS 核心与异步、浏览器原理与 CSS 布局、网络与安全、Vue 原理与工程化四大板块。