学习 Vue 3 时记下的模板语法、组件用法、响应式 API,以及路由和状态管理。
示例环境:HTML 示例中的 vue.js 需要自行提供 Vue 3 全局构建;单文件组件示例需要对应组件文件与依赖,接口示例需要自己的后端。
MVC和MVVM的架构模型
Vue 可借助 MVVM 理解,但它是渐进式界面框架;表单同步不改变组件间以 props 向下、事件向上的数据流。

基础语法
data属性
data() 为每个组件实例返回状态对象;不要将 Vue 3 的代理机制直接等同于 Vue 2 的 Object.defineProperty。
响应式数据拦截:Vue 3 主要通过 Proxy 跟踪对象属性的访问与修改。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h2>{{message}}</h2>
<button @click=changeMessage>changeMessage</button>
</div>
<script src="./vue.js"></script>
<script>
const app = Vue.createApp({
// data: option api
data() {
return {
message: "hello world"
}
},
// methods: option api
methods: {
changeMessage: function() {
this.message = "VUE"
},
},
})
app.mount("#app")
</script>
</body>
</html>
methods属性
需要组件 this 的方法使用普通函数,避免使用箭头函数。



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h2>{{count}}</h2>
<button @click="increase">+1</button>
<button @click="decrease">-1</button>
</div>
<script src="./vue.js"></script>
<script>
const app = Vue.createApp({
// data: option api
data() {
return {
count: 0
}
},
// methods: option api
methods: {
increase: function() {
this.count++
},
decrease: function() {
this.count--
}
},
})
app.mount("#app")
</script>
</body>
</html>
vue基础
模板语法

文本插值语法。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 基本使用 -->
<h2>{{ message }}</h2>
<h2>当前:{{ count }}</h2>
<h2>{{ count * 2 }}</h2>
<!-- 里面也可以写表达式 -->
<!-- 甚至 三元运算符 -->
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "hello vue",
count: 0
}
},
})
app.mount("#app")
</script>
</body>
</html>
v-once

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h2 v-once>{{ message }}</h2>
<button @click="changeMes">changeMes</button>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "hello vue"
}
},
methods: {
changeMes: function() {
this.message = "2333"
console.log(this.message);
}
},
})
app.mount("#app")
</script>
</body>
</html>
v-text

v-html
仅用于可信或适当净化的 HTML。内容不会作为 Vue 模板编译,也不能直接信任用户输入。

v-pre

v-cloak
需配合 [v-cloak] { display: none; };主要适用于无构建的 DOM 模板。

v-memo (3.2+) 性能优化用
v-memo 的依赖数组决定子树何时更新。下方示例只列 name,age 或 height 单独变化时可能不显示;需要同步展示时,应同时列入依赖。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app" v-memo="[name]">
<h2>{{ name }}</h2>
<h2>{{ age }}</h2>
<h2>{{ height }}</h2>
<button @click="updateInfo">改变信息</button>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
name: "why",
age: 213,
height: 1.88
}
},
methods: {
updateInfo: function() {
// 只有name改变才会重新渲染 优化性能 (超过1000个情况下)
this.name = "kobe"
}
},
})
app.mount("#app")
</script>
</body>
</html>
v-bind (重要)

绑定基本属性

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 切换图片功能 -->
<button @click="changeIMG">changeIMG</button>
<!-- 绑定img -->
<!-- <img v-bind:src="imgURL" alt=""> -->
<!-- 语法糖 -->
<img :src="imgShow ? imgURL1 : imgURL2" alt="">
<a :href="baiduURL">baidu</a>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
imgShow: true,
imgURL1: "https://images.unsplash.com/photo-1520209759809-a9bcb6cb3241?q=80&w=1170&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
imgURL2: "https://www.gokite.travel/wp-content/uploads/2025/02/2.-Experience-Thrills-Top-Rides-at-IMG-Adventure-Park-Dubai.webp",
baiduURL: "https://www.baidu.com"
}
},
methods: {
changeIMG: function() {
this.imgShow = !this.imgShow
}
},
})
app.mount("#app")
</script>
</body>
</html>
绑定class



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.active {
color: red
}
.bgc {
background-color: pink;
}
</style>
</head>
<body>
<div id="app">
<!-- 不同的状态下 有不同的class -->
<!-- 动态绑定 可以写 对象语法 -->
<!-- 对象语法的基本使用 -->
<button :class="{active: isActive}" @click="btnClick">change</button>
<!-- 动态绑定class 和 普通class 可以并列使用 -->
<!-- 数组语法的基本使用 -->
<h2 :class="['active', {bgc: isActive}]">hello world</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
isActive: false
}
},
methods: {
btnClick: function () {
this.isActive = !this.isActive
}
},
})
app.mount("#app")
</script>
</body>
</html>
绑定style


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 绑定style属性 -->
<!-- 属性名要写成驼峰命名法 -->
<!-- 对象写法 -->
<h2 :style="{color: color, fontSize: '42px'}">{{ message }}</h2>
<!-- 数组写法 -->
<h2 :style="[objStyle, {backgroundColor: 'pink'}]">{{ message }}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "hello vue",
color: "skyblue",
objStyle: {
color: this.color,
fontSiz: "30px"
}
}
},
})
app.mount("#app")
</script>
</body>
</html>
动态绑定属性

直接绑定对象

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- <h2 name="why" age="18" height="1.88">{{ message }}</h2> -->
<!-- 或者一个个绑定 太麻烦 -->
<!-- <h2 :name="name" :age="age" :height="height">{{ message }}</h2> -->
<!-- v-bind绑定对象 -->
<!-- 会自动遍历绑定 -->
<h2 v-bind="infos"></h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "hello vue",
infos: {
name: "why",
age: 18,
height: 1.88
},
name: "why",
age: 18,
height: 1.88
}
},
})
app.mount("#app")
</script>
</body>
</html>
事件绑定
v-on


v-on基本使用

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: orange;
}
</style>
</head>
<body>
<div id="app">
<!-- 基本写法 -->
<!-- <div class="box" v-on:click="divClick"></div> -->
<!-- 语法糖写法 -->
<div class="box" @click="divClick"></div>
<!-- 绑定方法的位置 也可以写成一个表达式 (不常用) -->
<!-- 不建议在模板中写js -->
<h2>{{ count }}</h2>
<button @click="count++">+1</button>
<button @click="count--">-1</button>
<!-- 绑定其他方法 -->
<div class="box" @mousemove="divMouseMove"></div>
<!-- 多个元素的事件绑定 -->
<div class="box" @click="divClick" @mousemove="divMouseMove"></div>
<!-- <div class="box" v-on="{click: divClick, mousemove: divMouseMove}"></div> -->
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
count: 0
}
},
methods: {
divClick() {
console.log("2333");
},
divMouseMove() {
console.log(1231231231);
},
},
})
app.mount("#app")
</script>
</body>
</html>
v-on参数传递

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<button @click="btn1Click">button1</button>
<button @click="btn2Click('why', 18)">button2</button>
<!-- 想要获取event对象 $event -->
<button @click="btn3Click('jack', 23, $event)">button3</button>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
}
},
methods: {
// 1.默认参数 event对象
// 绑定的时候没有传递任何的参数 event事件会默认传递进来
btn1Click(event) {
console.log(event);
},
// 2.明确参数
btn2Click(name, age) {
console.log(name, age);
},
btn3Click(name, age, event) {
console.log(name, age, event);
},
},
})
app.mount("#app")
</script>
</body>
</html>
v-on修饰符
.stop 阻止传播,.prevent 阻止默认行为;修饰符按书写顺序生效,不要组合 .passive 与 .prevent。

stopPropagation阻止事件冒泡
就是自动调用常用方法
条件渲染

v-if

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<ul v-if="names.length !== 0">
<li v-for="item in names">{{ item }}</li>
</ul>
<h2 v-else>当前没有数据,请获取数据再试!</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
names: ["abc", "cba", "nba"],
// names: [],
}
},
methods: {
},
})
app.mount("#app")
</script>
</body>
</html>
在 Vue 模板中,可以用带 v-if 等指令的 template 对多个节点分组。
div 会生成实际的 DOM 包裹元素。
上述 template 分组不会额外生成包裹元素;这不等同于所有 HTML template 标签的行为。
它在这里承担逻辑分组的作用。

v-show

v-if和v-show区别
v-if 创建或销毁子树,v-show 使用 display 切换可见性。v-show 不支持 template。

v-for

v-for的基本使用
Vue 模板的 v-for 同时支持 in 和 of 两种分隔写法。
这仅指 v-for 模板语法;JavaScript 的 for...in 与 for...of 并不等价。



数组更新检测

响应式数组仍可使用常见的 JavaScript 数组方法。
filter、map 等非变更方法需要将返回值赋回响应式状态;watch 能否触发取决于侦听源和配置,不能概括为“无法侦听”。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="item in names">{{ item }}</li>
</ul>
<button @click="changeList">change</button>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
names: ["abc", "csa", "ojp"]
}
},
methods: {
changeList() {
// this.names = ["why", "jack"]
// 通过一些方法修改数组中的元素
this.names.push("why")
// 不修改原数组的方法是不能监听的 watch
}
},
})
app.mount("#app")
</script>
</body>
</html>
v-for中key是什么作用?
key 应稳定且唯一。列表会增删、重排或包含输入状态时,不宜使用数组下标;template v-for 的 key 放在 template 上。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<!-- key要求是唯一标识 id -->
<li v-for="item in letters" :key="item">{{ item }}</li>
</ul>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
letters: [123, 123, 123, 3424235, 5463]
}
},
methods: {
},
})
app.mount("#app")
</script>
</body>
</html>
VNode
VNode 本质上是描述节点的 JavaScript 对象。










Options API

计算属性computed
computed 根据响应式依赖缓存派生值;getter 应保持无副作用。methods 每次调用执行,适合带参数计算和事件处理。





<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 直接拼接 不太好 -->
<!-- 直接写名称 不用写() -->
<h2>{{ fullName }}</h2>
<!-- 显示分数等级 -->
<h2>{{ scoreLevel }}</h2>
<!-- 反转单词文本 -->
<h2>{{ reverseText }}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
firstName: "kobe",
lastName: "Beyant",
score: 80,
text: "my name is why"
}
},
methods: {
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`
},
scoreLevel() {
return this.score >= 60 ? '及格' : '不及格'
},
reverseText() {
return this.text.split(" ").reverse().join(" ")
},
}
})
app.mount("#app")
</script>
</body>
</html>
computed vs methods
计算属性多次复用是有缓存的
不需要重新计算
依赖不变时可复用缓存结果;访问时写属性名,不需要调用括号


computed的set和get
通过 get 和 set 分别定义读取与写入规则;示例中的空 setter 本身不会更新姓名。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 直接拼接 不太好 -->
<!-- 直接写名称 不用写() -->
<h2>{{ fullName }}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
firstName: "kobe",
lastName: "Beyant",
}
},
methods: {
},
computed: {
fullName: {
get() {
return `${this.firstName} ${this.lastName}`
},
set() {
}
},
}
})
app.mount("#app")
</script>
</body>
</html>
侦听器 watch
对象展开只是浅拷贝,不是深快照;toRaw 返回原始对象,但直接修改它不会可靠地驱动响应式更新。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h2>{{ message }}</h2>
<h2>{{ info }}</h2>
<button @click="changeMessage">修改</button>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "hello vue",
info: { name: "why", age: 18 }
}
},
methods: {
changeMessage() {
this.message = "hello world"
this.info = {name: "kobe"}
}
},
watch: {
message(newVal, oldVal) {
console.log("message发生了改变", newVal, oldVal);
},
// 如果是对象类型 返回的是proxy
info(newVal, oldVal) {
console.log("info发生了变化", newVal, oldVal);
// 获取原始对象 (直接解构)
console.log({...newVal}, {...oldVal});
// 获取原始对象 (Vue.toRaw())
console.log(Vue.toRaw(newVal), Vue.toRaw(oldVal));
},
}
})
app.mount("#app")
</script>
</body>
</html>

watch侦听器的配置选项
深层修改时,新旧值可能指向同一对象。immediate 表示立即执行回调;读取更新后的 DOM 使用 flush: post 或 nextTick。




<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h2>{{ info.name }}</h2>
<button @click="changeInfo">修改</button>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
info: { name: "why", age: 18 }
}
},
methods: {
changeInfo() {
// 只是在改变属性
this.info.name = "kobe"
}
},
watch: {
// 默认 没有开启 深度监听 deep
info: {
handler(newVal, oldVal) {
console.log("修改了info", newVal, oldVal)
console.log(newVal === oldVal);
},
// 进行深度监听
deep: true,
// 第一次渲染的时候 执行渲染器
immediate: true,
},
"info.name": function(newVal, oldVal) {
console.log(newVal, oldVal);
},
},
})
app.mount("#app")
</script>
</body>
</html>
综合案例
列表用 :key 绑定唯一标识,商品数量递减时不能小于 0。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
border-collapse: collapse;
text-align: center;
background-color: whitesmoke;
}
th,
td {
border: 2px solid gray;
padding: 8px 16px;
}
.active {
background-color: skyblue;
}
</style>
</head>
<body>
<div id="app">
<template v-if="books.length === 0">
<h2>购物车为空,请添加书籍!</h2>
</template>
<template v-else>
<table>
<thead>
<tr>
<th>序号</th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in books" :key="item.id" :class="{active: index === curIndex}">
<td @click="clickIndex(index)">{{ index + 1 }}</td>
<td @click="clickIndex(index)">{{ item.name }}</td>
<td @click="clickIndex(index)">{{ item.date }}</td>
<td @click="clickIndex(index)">{{ formatPrice(item.price) }}</td>
<td>
<button :disabled="item.count === 0" @click="decrement(index),clickIndex(index)">-</button>
{{ item.count }}
<button @click="increment(index),clickIndex(index)">+</button>
</td>
<td>
<button @click="removeItem(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价:{{ formatPrice(totalPrice) }}</h2>
</template>
</div>
<script src="../vue.js"></script>
<script src="./data.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
books: books,
curIndex: -1,
}
},
methods: {
formatPrice(price) {
return `¥${price}`
},
clickIndex(index) {
this.curIndex = index
},
increment(index) {
this.books[index].count++
},
decrement(index) {
if (this.books[index].count > 0) this.books[index].count--
},
removeItem(index) {
this.books.splice(index, 1)
this.curIndex = -1
}
},
computed: {
totalPrice() {
let total = 0
this.books.forEach(element => total += element.price * element.count);
return total
},
}
})
app.mount("#app")
</script>
</body>
</html>
const books = [
{
id: 1,
name: '《算法导论》',
date: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: '《UNIX编程艺术》',
date: '2006-2',
price: 59.00,
count: 1
},
{
id: 3,
name: '《编程珠玑》',
date: '2008-10',
price: 39.00,
count: 1
},
{
id: 4,
name: '《代码大全》',
date: '2006-3',
price: 128.00,
count: 1
},
{
id: 5,
name: '《你不知道JavaScript》',
date: '2014-8',
price: 88.00,
count: 1
},
]
v-model 表单
v-model的基本使用


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<label for="account">
<input type="text" v-model="account">
</label>
<label for="password">
<input type="password" v-model="password">
</label>
<!-- <input type=" text" :value="message" @input="inputChange"> -->
<!-- 等价于上面的效果 -->
<!-- 双向绑定 -->
<input type="text" v-model="message">
<h2>{{ account }}</h2>
<h2>{{ password }}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "hello vue",
account: "",
password: "",
}
},
methods: {
// inputChange(event) {
// this.message = event.target.value
// }
},
})
app.mount("#app")
</script>
</body>
</html>

v-model绑定textarea

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<textarea cols="30" rows="10" v-model="message"></textarea>
<h2>{{ message }}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "hello vue"
}
},
methods: {
},
})
app.mount("#app")
</script>
</body>
</html>
v-model绑定checkbox

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<label for="agree">
<!-- 单选框 绑定过去的值 是Boolean -->
<input id="agree" type="checkbox" v-model="isAgree" >同意协议
</label>
<h2>{{ isAgree }}</h2>
<hr>
<!-- 多选框 -->
<!-- 注意:多选框要明确绑定一个value值 -->
<!-- 绑定到一个数组中 选中会把value添加到数组中 -->
<div class="hobbies">
<label for="basketball">
<input type="checkbox" id="basketball" v-model="hobbies" value="basketball">basketball
</label>
<label for="sing">
<input type="checkbox" id="sing" v-model="hobbies" value="sing">sing
</label>
<label for="jump">
<input type="checkbox" id="jump" v-model="hobbies" value="jump">jump
</label>
<label for="rap">
<input type="checkbox" id="rap" v-model="hobbies" value="rap">rap
</label>
</div>
<h2>{{ hobbies }}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
isAgree: false,
hobbies: [],
}
},
methods: {
},
})
app.mount("#app")
</script>
</body>
</html>
v-model绑定radio

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 通过设置name让不同的radio互斥 -->
<!-- 因为绑定同一个v-model 同样可以起到互斥的效果 -->
<!-- 通过设置value 传输数据 -->
<div id="app">
<div class="gender">
<label for="male">
<input type="radio" v-model="gender" value="male">male
</label>
<label for="female">
<input type="radio" v-model="gender" value="female">female
</label>
</div>
<h2>{{ gender }}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
// 默认选中直接写
gender: "male"
}
},
methods: {
},
})
app.mount("#app")
</script>
</body>
</html>
v-model绑定select

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- select单选 -->
<select v-model="message">
<option value="apple">apple</option>
<option value="orange">orange</option>
<option value="banana">banana</option>
</select>
<h2>{{ message }}</h2>
<hr>
<!-- select多选 -->
<select multiple size="2" v-model="fruits">
<option value="apple">apple</option>
<option value="orange">orange</option>
<option value="banana">banana</option>
</select>
<h2>{{ fruits }}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "",
fruits: []
}
},
methods: {
},
})
app.mount("#app")
</script>
</body>
</html>
v-model值的绑定

数据不是写死的,是服务器动态绑定的
用v-for和v-bind来完成
v-model修饰符
.lazy 使用 change 事件;.trim 去除首尾空白;.number 尝试数值转换,但空输入仍可能为空字符串,不能代替校验。



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- lazy:绑定change事件 -->
<!-- change事件 失去焦点/提交 才会变更 -->
<input type="text" v-model.lazy="message">
<h2>{{ message }}</h2>
<!-- number:自动将内容转化为数字 -->
<input type="text" v-model.number="count">
<!-- 只能输入数字 没必要用number -->
<input type="number" v-model="count">
<h2>{{ count }}-{{ typeof count }}</h2>
<!-- trim:去除首尾的空格 -->
<!-- 多个空格连起来 浏览器会渲染成一个空格 -->
<input type="text" v-model.trim="content">
<h2>{{ content }}</h2>
<!-- 多个修饰符连用的话 就多个.加在后面 -->
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
message: "hello vue",
count: 0,
content: "",
}
},
methods: {
},
})
app.mount("#app")
</script>
</body>
</html>

组件化基础-脚手架
基础概念




组件的注册方式

注册全局组件


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 使用product-item -->
<product-item></product-item>
<product-item></product-item>
<product-item></product-item>
</div>
<script src="../vue.js"></script>
<script>
// 组件App根组件
const App = {}
// 开发一个productItem组件
const productItem = {
template: `<h1>我是一个组件</h1>`
}
// 创建app
const app = Vue.createApp(App)
// 注册全局组件
// 组件名称 - 对象
app.component("product-item", productItem)
// 挂载app
app.mount("#app")
</script>
</body>
</html>
组件的名称

注册局部组件


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<product-item></product-item>
<product-item></product-item>
<product-item></product-item>
</div>
<script src="../vue.js"></script>
<script>
const app = Vue.createApp({
components: {
"product-item": {
template: `<h1>我是一个组件</h1>`
}
},
data() {
return {
}
},
methods: {
},
})
app.mount("#app")
</script>
</body>
</html>
vue的开发模式





VUE-CLI的使用
Vue CLI 已进入维护模式,新项目可使用 create-vue 与 Vite。
npm i -g @vue/cli
vue create my-project
vue create my-project --packageManager pnpm
npm -g update




组件化-组件间通信
组件的嵌套


组件的通信


父传子 props(数组/对象)
对象和数组的 default 通常使用工厂函数;props 浅只读,内部可变对象也应通过明确的数据流修改。
<template>
<div class="infos">
<h2>{{ name }}</h2>
<h2>{{ age }}</h2>
<h2>{{ height }}</h2>
</div>
</template>
<script>
export default {
// props 数组 (父传子)
// 数组语法的弊端:
// 1.不能对类型进行验证
// 2.没有默认值的
// props: ["name", "age", "height"]
// props 对象 (父传子)
// 对象语法(必须)
// 如果类型type 是Object对象类型 包括array
// 需要用函数返回 () => ({ name: "jack" })
props: {
name: {
type: String,
default: "默认值"
},
age: Number,
height: Number
}
}
</script>






非prop的attribute
未声明为 props 或 emits 的属性和监听器属于 $attrs。单根组件通常自动透传,多根组件需明确绑定位置。


子传父 emit
<template>
<div class="app">
<h2>当前计数: {{ counter }}</h2>
<AddCounter @add="btnAdd"></AddCounter>
<SubCounter @sub="btnSub"></SubCounter>
</div>
</template>
<script>
import AddCounter from './components/AddCounter.vue';
import SubCounter from './components/SubCounter.vue';
export default {
components: {
AddCounter,
SubCounter,
},
data() {
return {
counter: 0
}
},
methods: {
btnAdd(count) {
this.counter += count
},
btnSub(count) {
this.counter -= count
}
}
}
</script>
<style scoped></style>
<template>
<div class="add">
<button @click="btnClick(1)">+1</button>
<button @click="btnClick(5)">+5</button>
<button @click="btnClick(10)">+10</button>
</div>
</template>
<script>
export default {
emits: ["add"],
methods: {
btnClick(count) {
// 让子组件发送一个自定义事件
// 第一个是事件名称 后面是参数
this.$emit("add", count)
}
}
}
</script>
<style scoped>
</style>


自定义事件的参数验证
emits 校验失败只产生开发期警告,不会自动阻止事件;业务上不允许的操作需在 emit 前判断。组件事件不会像 DOM 事件一样冒泡。


组件化-插槽Slot/非父子通信

插槽的基本使用
<template>
<div class="app">
<ShowMessage title="哈哈哈">
<button>我是按钮</button>
</ShowMessage>
<ShowMessage title="哈哈哈">
<p>我是内容</p>
</ShowMessage>
<ShowMessage title="233"></ShowMessage>
</div>
</template>
<script>
import ShowMessage from './components/ShowMessage.vue';
export default {
components: {
ShowMessage,
},
}
</script>
<style scoped></style>
<template>
<h2>{{ title }}</h2>
<div class="content">
<slot>
<p>我是默认值</p>
</slot>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: "",
},
},
data() {
return {
}
},
}
</script>
<style scoped></style>




具名插槽(针对多个插槽)
<template>
<div class="app">
<NavBar>
<template v-slot:left>
<button>返回</button>
</template>
<template v-slot:center>
<a href="#">登录</a>
</template>
<template v-slot:right>
<div>现在</div>
</template>
<template v-slot:default>
<p>233</p>
</template>
</NavBar>
</div>
</template>
<script>
import NavBar from './components/NavBar.vue';
export default {
components: {
NavBar,
},
}
</script>
<style scoped></style>
<template>
<div class="nav-bar">
<div class="left">
<slot name="left">left</slot>
</div>
<div class="center">
<slot name="center">right</slot>
</div>
<div class="right">
<slot name="right">right</slot>
</div>
</div>
<div class="other">
<slot></slot>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
.nav-bar {
display: flex;
height: 44px;
line-height: 44px;
text-align: center;
}
.left {
width: 80px;
background-color: skyblue;
}
.center {
flex: 1;
background-color: orange;
}
.right {
width: 80px;
background-color: aquamarine;
}
</style>

动态插槽名
<template>
<div class="app">
<NavBar>
<template v-slot:left>
<button>返回</button>
</template>
<template v-slot:center>
<a href="#">登录</a>
</template>
<template v-slot:right>
<div>现在</div>
</template>
<template v-slot:default>
<p>233</p>
</template>
</NavBar>
<!-- nav-bar只给一个插槽传入数据 -->
<!-- 动态插槽名 -->
<NavBar>
<template v-slot:[position]>
<a href="#">注册</a>
</template>
</NavBar>
<button @click="position = 'left'">左边</button>
<button @click="position = 'center'">中间</button>
<button @click="position = 'right'">右边</button>
</div>
</template>
<script>
import NavBar from './components/NavBar.vue';
export default {
components: {
NavBar,
},
data() {
return {
position: 'left',
}
},
}
</script>
<style scoped></style>

具名插槽的缩写 #header

渲染作用域
父级编写的插槽内容使用父级作用域;子级数据通过 slot props 显式传出。


作用域插槽
<template>
<div class="app">
<TabControl :titles="['衣服', '裤子', '鞋子']" @tab-item-click="tabItemClick">
<template #default="data">
<button>{{ data.item }}</button>
</template>
</TabControl>
<h1>{{ pageContent[curIndex] }}</h1>
</div>
</template>
<script>
import TabControl from './components/TabControl.vue';
export default {
components: {
TabControl,
},
data() {
return {
curIndex: 0,
pageContent: ["衣服页面", "裤子页面", "鞋子页面"],
}
},
methods: {
tabItemClick(index) {
this.curIndex = index
}
},
}
</script>
<style scoped></style>
<template>
<div class="tab-control">
<template v-for="(item, index) in titles" :key="index">
<div class="tab-control-item"
:class="{ active: curIndex === index }"
@click="clickIndex(index)">
<slot :item="item">
{{ item }}
</slot>
</div>
</template>
</div>
</template>
<script>
export default {
emits: ["tabItemClick"],
props: {
titles: {
type: Array,
default: () => []
}
},
data() {
return {
curIndex: 0,
}
},
methods: {
clickIndex(index) {
this.curIndex = index
this.$emit("tabItemClick", this.curIndex)
}
}
}
</script>




非父子组件通信
provide/inject 负责子树依赖传递,Pinia 管理共享业务状态,二者可以同时使用。

全局事件总线
Vue 3 移除了组件实例上的 $on、$off、$once。若使用外部事件总线,需在生命周期结束时取消订阅。



provide和inject (依赖注入)
传递 ref 或 computed 可保持响应式联系;普通值的一次赋值不会自动同步。computed 的 getter 需要返回计算结果。



<template>
<div class="app">
<Home></Home>
</div>
</template>
<script>
import { computed } from 'vue';
import Home from './components/Home.vue';
export default {
components: {
Home,
},
// provide: {
// name: "why",
// age: 18
// },
data() {
return {
message: "hello world"
}
},
// 这种写法 才能绑定this
// 这样message 才会更新 不是简单的赋值
provide() {
return {
name: "why",
age: 18,
message: computed(() => {
return this.message
})
}
}
}
</script>
<style scoped></style>
<template>
<div class="home-banner">
<h2>{{ name }}</h2>
<h2>{{ age }}</h2>
</div>
</template>
<script>
export default {
inject: ["name", "age"]
}
</script>
<style scoped></style>

组件化-额外知识补充
生命周期(重点)
钩子在 setup 同步执行时登记。挂载后才能访问模板 DOM;卸载时清理监听器、定时器和未完成请求。




mounted 获取DOM(被挂载了)
unmounted 回收操作(取消事件监听)
组件中的 $refs 引用:获取 DOM(重点)
模板引用在挂载前或 v-if 卸载后可能为 null。状态更新后若要读新 DOM,先 await nextTick;script setup 组件用 defineExpose 公开必要方法。
<template>
<div class="app">
<h2 ref="title">{{ message }}</h2>
<button ref="btn" @click="changeTitle">change</button>
</div>
</template>
<script>
export default {
data() {
return {
message: "hello world",
}
},
methods: {
changeTitle() {
// this.message = "你好啊"
// 获取h2/btn元素
console.log(this.$refs.title);
console.log(this.$refs.btn);
}
}
}
</script>


动态组件
<template>
<div class="app">
<div class="tabs">
<template v-for="(item, index) in tabs" :key="item">
<button :class="{ active: curIndex === index }"
@click="curIndex = index">
{{ item }}
</button>
</template>
</div>
<div class="views">
<!-- 方法1: 通过v-if实现 -->
<!-- 方法2: 动态组件 -->
<component :is="tabs[curIndex]"></component>
</div>
</div>
</template>
<script>
import About from "./views/About.vue";
import Category from "./views/Category.vue";
import Home from "./views/Home.vue";
export default {
components: {
Home,
About,
Category,
},
data() {
return {
tabs: ["home", "about", "category"],
curIndex: 0,
};
},
};
</script>
<style scoped>
.active {
color: red;
}
</style>




keep-alive
include/exclude 按组件 name 匹配,max 限制缓存数。缓存组件停用时不会立即卸载,应按需在 activated/deactivated 中恢复或暂停资源。
<!-- 状态会丢失 例如计数器等等 -->
<template>
<div class="app">
<div class="tabs">
<template v-for="(item, index) in tabs" :key="item">
<button :class="{ active: curIndex === index }" @click="curIndex = index">
{{ item }}
</button>
</template>
</div>
<div class="views">
<!-- 方法1: 通过v-if实现 -->
<!-- 方法2: 动态组件 -->
<!-- include 来自于name属性 -->
<keep-alive include="Home">
<component :is="tabs[curIndex]"></component>
</keep-alive>
</div>
</div>
</template>
<script>
import About from "./views/About.vue";
import Category from "./views/Category.vue";
import Home from "./views/Home.vue";
export default {
components: {
Home,
About,
Category,
},
data() {
return {
tabs: ["home", "about", "category"],
curIndex: 0,
};
},
};
</script>
<style scoped>
.active {
color: red;
}
</style>
<template>
<div class="home">
<h2>home组件</h2>
<h2>{{ counter }}</h2>
<button @click="counter++">+1</button>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
counter: 0
}
}
}
</script>
<style scoped></style>



webpack代码分包概念介绍

vue实现异步组件
defineAsyncComponent 包装异步组件,动态 import 允许分包;路由懒加载直接使用 component: () => import(...)。
<template>
<div class="app">
<div class="tabs">
<template v-for="(item, index) in tabs" :key="item">
<button :class="{ active: curIndex === index }" @click="curIndex = index">
{{ item }}
</button>
</template>
</div>
<div class="views">
<!-- 方法1: 通过v-if实现 -->
<!-- 方法2: 动态组件 -->
<!-- include 来自于name属性 -->
<keep-alive include="Home">
<component :is="tabs[curIndex]"></component>
</keep-alive>
</div>
</div>
</template>
<script>
import { defineAsyncComponent } from "vue";
import Home from "./views/Home.vue";
import About from "./views/About.vue";
// import Category from "./views/Category.vue";
const AsyncCategory = defineAsyncComponent(() => import("./views/Category.vue"))
export default {
components: {
Home,
About,
Category: AsyncCategory,
},
data() {
return {
tabs: ["home", "about", "category"],
curIndex: 0,
};
},
};
</script>
<style scoped>
.active {
color: red;
}
</style>


组件的v-model
modelValue + update:modelValue 是 Vue 3 组件双向绑定的约定,Vue 3.4+ 可用 defineModel 简化。
<template>
<div class="app">
<!-- input v-model -->
<input v-model="message">
<input :value="message" @input="message = $event.target.value">
<!-- 组件v-model -->
<Counter v-model="appCounter"></Counter>
<Counter :modelValue="appCounter" @update:modelValue="appCounter = $event"></Counter>
</div>
</template>
<script>
import Counter from './Counter.vue';
export default {
data() {
return {
message: "hello world",
appCounter: 100,
}
},
components: {
Counter,
},
}
</script>
<style scoped></style>
<template>
<div class="counter">
<h2>counter: {{ modelValue }}</h2>
<button @click="changeCounter">修改数据</button>
</div>
</template>
<script>
export default {
props: {
modelValue: {
type: Number,
default: 0,
}
},
emits: ["update:modelValue"],
methods: {
changeCounter() {
this.$emit("update:modelValue", 99)
}
}
}
</script>
<style scoped></style>



mixin
Options API 仍支持 mixin。新逻辑通常用 composable 显式组织依赖和返回值,更容易避免同名冲突。
<template>
<div class="home">
<h2>home组件</h2>
</div>
</template>
<script>
import messageMixin from './mixins/message-mixin';
export default {
mixins: [messageMixin]
}
</script>
<style scoped></style>
export default {
data() {
return {
message: "hello world",
};
},
};




Composition API (组合式API)



setup函数
setup 不使用组件 this;普通 setup 需返回模板所需绑定。下方 script setup 示例要求 Vue 3.2+,顶层绑定自动供模板使用。

data修改

<template>
<div class="app">
<h2>{{ title }}</h2>
<h2>{{ message }}</h2>
<button @click="changeMessage">change</button>
</div>
</template>
<script setup>
import { reactive, ref } from 'vue';
// 定义简单数据类型 (ref也可以定义复杂数据类型)
let title = ref("hello world")
// 定义复杂数据类型
let message = reactive({
username: "coderwhy",
password: "2133245",
})
function changeMessage() {
message.username = "hahahaha"
}
</script>
<style lang="scss" scoped></style>
Reactive API (定义复杂类型数据)
reactive 适用于对象、数组、Map、Set 等,不适用于原始类型。需整体替换状态时可用 ref;保留代理引用才能维持既有依赖。

ref:原始类型与对象
ref 既能保存原始类型,也能保存对象和数组;JavaScript 中用 .value,模板中的顶层 ref 通常自动解包。


Vue 的单向数据流规范
props 是浅只读约束;子组件不应通过嵌套属性变更绕过清晰的状态归属。
数据从父组件流向子组件(Props向下传递)
子组件不能直接修改父组件的Props数据
若要修改,必须通过emit事件通知父组件,由父组件自身来更新数据
这保证了数据流向清晰、可追溯,使应用状态管理更稳定和易维护
readonly的使用
readonly 创建只读视图,但原始持有者仍可通过可写状态更新数据;它不会冻结整个数据来源。



Reactive判断的api

toRefs/toRef
普通解构原始类型属性会断开响应式联系,toRef/toRefs 可保持联系;toFixed 返回字符串,需要数值时再转为 Number。
<template>
<div class="app">
<h2>{{ name }} - {{ age }}-{{ height }}</h2>
<button @click="increase">+1</button>
<button @click="decrease">-0.1</button>
</div>
</template>
<script setup>
import { reactive, toRef, toRefs } from 'vue';
const info = reactive({
name: "why",
age: 18,
height: 1.99
})
// 被解构后为了防止失去响应式
const { name, age } = toRefs(info)
const height = toRef(info, "height")
function increase() {
info.age++
}
function decrease() {
info.height -= 0.1
info.height = Number(info.height.toFixed(2))
}
</script>
<style lang="scss" scoped></style>




其他


computed
<template>
<div class="app">
<h2>{{ fullName }}</h2>
<h2>{{ fullName }}</h2>
<h2>{{ fullName }}</h2>
<button @click="setFullname">changeFullname</button>
</div>
</template>
<script setup>
import { computed, reactive } from 'vue';
const names = reactive({
firstName: "kobe",
lastName: "black",
})
// const fullName = computed(() => {
// return names.firstName + " " + names.lastName
// })
const fullName = computed({
get: function() {
return names.firstName + " " + names.lastName
},
set: function(newVal) {
const tempName = newVal.split(" ")
names.firstName = tempName[0]
names.lastName = tempName[1]
}
})
function setFullname() {
fullName.value = "coder why"
}
</script>
<style lang="scss" scoped></style>

setup中的ref($ref获取DOM)
<template>
<div class="app">
<h2 ref="titleRef">hello world</h2>
<button @click="getElement">getElement</button>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
const titleRef = ref()
// mounted生命周期函数
onMounted(() => {
console.log(titleRef.value);
})
function getElement() {
console.log(titleRef.value);
}
</script>
<style lang="scss" scoped></style>

生命周期钩子
组件卸载前的钩子是 onBeforeUnmount。Vue 3.5+ 还可用 useTemplateRef 处理模板引用。
onBeforeMount
onMounted
onBeforeUpdate
onUpdated
onBeforeUnmount
....



provide/inject:依赖注入
依赖注入适合主题、表单等子树上下文,可与 Pinia 配合使用。


watch/watchEffect
watch 明确指定来源;watchEffect 立即执行并收集同步读取的依赖,首个 await 之后的读取不会自动追踪。首次同步执行时,不能调用尚未初始化的 stopWatch;请求类副作用还应登记清理。
<template>
<div class="app">
<h2>{{ counter }}</h2>
<button @click="counter++">+1</button>
<button @click="message = '2333'">修改message</button>
<button @click="info.age = 22">修改info</button>
</div>
</template>
<script setup>
import { reactive, ref, watch, watchEffect } from 'vue';
let counter = ref(0)
let message = ref("hello world")
let info = reactive({
name: "jack",
age: 18
})
// 监听数据变量
watch(message, (newVal, oldVal) => {
console.log(newVal, oldVal);
})
watch(info, (newVal, oldVal) => {
console.log(newVal, oldVal);
}, {
immediate: true
})
// 监听数据变化后,获取普通数据对象
// 原来是proxy 结构成一个普通对象
// 侦听多个源 放到一个数组中
watch(() => ({ ...info }), (newVal, oldVal) => {
console.log(newVal, oldVal);
})
// 监听counter的变化
// 可以用watch
// 1.watchEffect传入的函数默认会直接被执行
// 2.在执行的过程之中,会自动收集依赖(依赖响应式的数据)
const stopWatch = watchEffect(() => {
console.log("-----", counter.value, message.value);
if (counter.value >= 10) {
stopWatch()
}
})
</script>
<style lang="scss" scoped></style>






hook练习 (demo)



setup语法
defineProps、defineEmits、defineExpose 为编译宏,无需导入。defineExpose 用于公开组件方法,例如 infoBtnClick。Vue 3.5+ 的 props 解构编译优化不等同于普通 reactive 解构。



// 定义props
const props = defineProps({
name: {
type: String,
default: "",
}
})
const emits = defineEmits(["infoBtnClick"])
function infoBtnClick() {}
defineExpose({
foo: infoBtnClick,
})

















VUE-router
前端路由的发展





认识vue-router
入口需注册 router,并创建所引用的视图文件。Vue 3 对应 Vue Router 4。
<template>
<div class="app">
<h2>app</h2>
<div class="nav">
<!-- 写active-class会重命名 router-link-active -->
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<router-link to="/user/123">用户123</router-link>
<router-link to="/user/321">用户321</router-link>
<router-link to="/order">订单</router-link>
<button @click="logoutClick">推出登录</button>
</div>
<router-view></router-view>
</div>
</template>
<script setup>
function logoutClick() {
localStorage.removeItem("token")
}
</script>
<style scoped>
.router-link-active {
color: skyblue;
font-size: 20px;
}
</style>
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
import { createRouter } from "vue-router";
import { createWebHashHistory } from "vue-router";
import { createWebHistory } from "vue-router";
// import Home from "../views/Home.vue";
// import About from "../views/About.vue";
// 分包操作 (路由的懒加载)
// const Home = () => import("../views/Home.vue")
// const About = () => import("../views/About.vue")
// 创建一个路由:映射关系
const router = createRouter({
// history: createWebHashHistory(),
history: createWebHistory(),
routes: [
// 进入页面的时候 直接到home
{
path: "/",
redirect: "/home",
},
{
// 可以增加name属性 独一无二的
name: "home",
path: "/home",
component: () => import("../views/Home.vue"),
// 可以往 meta里面加东西
// meta: {},
// 路由的嵌套 children
children: [
{
path: "",
redirect: "/home/recommend",
},
{
// path 变为了子路径
path: "recommend",
component: () => import("../views/HomeRecommend.vue"),
},
{
path: "ranking",
component: () => import("../views/HomeRanking.vue"),
},
],
},
{
path: "/about",
component: () => import("../views/About.vue"),
},
{
name: "user",
// 后面不是写死的 后面可能跟上id (动态路由)
path: "/user/:id",
component: () => import("../views/User.vue"),
},
{
name: "NotFound",
// 表示匹配不到具体的路径
// path: "/:pathMatch(.*)*", 会放到一个数组中
path: "/:pathMatch(.*)",
component: () => import("../views/NotFound.vue"),
},
{
name: "order",
path: "/order",
component: () => import("../views/Order.vue")
},
{
name: "login",
path: "/login",
component: () => import("../views/Login.vue")
}
],
});
// 动态路由
let isAdmin = true
if (isAdmin) {
// 一级路由
router.addRoute({
path: "/admin",
component: () => import("../views/Admin.vue")
})
// 添加二级路由
router.addRoute("home", {
path: "songs",
component: () => import("../views/HomeSongs.vue")
})
}
// 获取所有路由记录的数组
// console.log(router.getRoutes());
// 路由导航守卫 guard
// 进行任何路由跳转之前 传入的beforeEach中的函数都会被回调
// (有点像watch 拦截的意思)
router.beforeEach((to, from) => {
const token = localStorage.getItem("token")
if (to.path === "/order" && !token) {
return "/login"
}
// 进入到任何别的页面时 判断用户是否登录
// if (to.path !== "/login") {
// return "/login"
// }
})
export default router;
<template>
<div class="home">
<h2>home组件</h2>
<div class="nav">
<router-link to="/home/recommend">推荐</router-link>
<router-link to="/home/ranking">排行</router-link>
</div>
<router-view></router-view>
<!-- 编程式路由的跳转 -->
<button @click="aboutBtnClick">跳转到about</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter()
function aboutBtnClick() {
// router.push("/about")
router.push({
path: "/about",
// 可以传参
query: {
userName: "why",
age: 18,
}
})
}
</script>
<style lang="scss" scoped></style>



路由的默认路径
嵌套路由的默认子路径写作空字符串。HTML5 history 模式部署时,需要服务器将应用路由回退到入口 HTML。


router-link的属性

路由懒加载


路由的其他属性

动态路由基本匹配
同一路由仅参数变化时可能复用组件,需侦听相关 route.params 或使用更新守卫;不是每次参数变化都会重新挂载。




路由的嵌套


编程时路由的跳转
带 params 时优先使用命名路由;传 path 时 params 不会自动拼入。push 新增历史记录,replace 替换当前记录。



编程时页面的前进后退

动态管理路由

删除动态路由(了解)

路由导航守卫。


导航守卫的解析流程
依次经过离开守卫、beforeEach、复用组件更新守卫、beforeEnter、异步组件、beforeRouteEnter、beforeResolve,再确认导航、afterEach 与 DOM 更新。前端 token 判断不能代替后端鉴权。

vuex状态管理
Vuex 4 支持 Vue 3;新项目可使用 Pinia。mutation 必须同步,异步业务放在 action。




vuex的安装

创建store
示例 store 按 modules.home 组织,未启用 namespaced,getters/mutations 使用全局名称。/api/example 需要自行实现。
<template>
<div class="app">
<h2>{{ $store.state.home.counter }}</h2>
<Home></Home>
<button @click="increment()">+1</button>
</div>
</template>
<script setup>
import { useStore } from "vuex";
import Home from "./views/Home.vue"
// 想要修改数据 必须用mutations
const store = useStore()
// function increment() {
// store.commit("increment")
// }
// 不用像上面那样写了 用useStore + commit替代
const increment = () => store.commit("increment")
// function increment() {
// store.dispatch(increment)
// }
</script>
<style lang="scss" scoped></style>
import { createStore } from "vuex"
import homeModules from "./modules/home"
const store = createStore({
state: () => ({
}),
// 对state的数据进行处理
getters: {
},
mutations: {
},
actions: {
},
modules: {
home: homeModules,
}
})
export default store
export default {
state: () => ({
counter: 100,
name: "coderwhy",
level: 25,
}),
mutations: {
increment(state) {
state.counter++;
},
},
getters: {
doubleCounter(state) {
return state.counter * 2;
},
},
actions: {
async incrementAction(context) {
// context.commit 用于提交mutation
// getters state
const res = await fetch("/api/example");
const data = await res.json();
context.commit("increment");
},
},
};
<template>
<div class="home">
<h2>{{ $store.state.home.counter }}</h2>
<h2>{{ name }}</h2>
<h2>{{ level }}</h2>
<h2>{{ doubleCounter }}</h2>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';
// mapState针对options API可以 (借助于this解构)
// 官方推荐用store.state
const store = useStore()
const name = computed(() => store.state.home.name)
const level = computed(() => store.state.home.level)
const doubleCounter = computed(() => store.getters.doubleCounter)
</script>
<style lang="scss" scoped></style>
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')


单一状态树


映射mapState
<template>
<div class="home">
<h2>{{ $store.state.counter }}</h2>
<h2>{{ name }}</h2>
<h2>{{ level }}</h2>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';
// mapState针对options API可以 (借助于this解构)
// 官方推荐用store.state
const store = useStore()
const name = computed(() => store.state.name)
const level = computed(() => store.state.level)
</script>
<style lang="scss" scoped></style>

getters的基本使用
getters 对 state 派生计算并返回结果,getter 中应避免修改状态。
通过 store.getters 读取 getter;使用命名空间时还需包含模块前缀。



mapGetters的辅助函数

Mutation基本使用


Mutation常量类型

mapMutations辅助函数


actions的基本使用



actions的异步操作

module的基本使用


命名空间namespaced
开启 namespaced: true 后,commit、dispatch 与 getter 访问都应包含模块前缀;mapState 等辅助函数也可传模块名。


pinia状态管理



store
import { createApp } from "vue";
import App from "./App.vue";
import pinia from "./stores";
createApp(App).use(pinia).mount("#app");
import { createPinia } from "pinia";
const pinia = createPinia();
export default pinia
import { defineStore } from "pinia";
const useUser = defineStore("user", {
state: () => ({
name: "why",
age: 22,
level: 100,
}),
actions: {
increment() {
this.age++
},
async fetchData() {
const res = await fetch("xxx")
const data = res.json()
return data
}
}
});
export default useUser;
// 定义一个关于counter的store
import { defineStore } from "pinia";
const useCounter = defineStore("counter", {
state: () => ({
count: 99,
}),
getters: {
doubleCount(state) {
return state.count * 2
},
doubleCountAddone(state) {
return this.doubleCount + 1
}
},
})
export default useCounter
<template>
<div class="home">
<h2>home page</h2>
<h2>{{ count }}</h2>
<h2>{{ doubleCount }}</h2>
<h2>{{ doubleCountAddone }}</h2>
<hr>
<h2>{{ name }} {{ age }} {{ level }}</h2>
<button @click="changeUser">changeUser</button>
<button @click="resetUser">reset user</button>
<button @click="increment()">age + 1</button>
</div>
</template>
<script setup>
import useCounter from '@/stores/counter';
import useUser from '@/stores/user';
import { storeToRefs } from 'pinia';
const counterStore = useCounter()
const userStore = useUser()
const {
count,
doubleCount,
doubleCountAddone
} = storeToRefs(counterStore)
const {
name,
age,
level,
} = storeToRefs(userStore)
function increment() {
userStore.increment()
}
function fetchData() {
userStore.fetchData().then(res => {
console.log(res);
})
}
function changeUser() {
// 一个个修改 (正常就这样用)
userStore.name = "Jack"
userStore.age = 25
userStore.level = 200
// 一次性修改多个数据
// userStore.$patch({
// name: "james",
// age: 34,
// })
// 替换state为一个新的对象
// userStore.$state = {
// name: "curry",
// level: 200
// }
}
function resetUser() {
userStore.$reset()
}
</script>
<style lang="scss" scoped></style>



state

state修改-重置
Pinia 可直接修改 state 或用 $patch。Option Store 内置 $reset,Setup Store 需自行实现;给 $state 赋值实际通过 patch 更新,不是直接替换响应式对象。


认识和定义getters
storeToRefs 用于解构 state 与 getters;action 可以直接解构。TypeScript 中依赖 this 的 getter 需标注返回类型。



定义和认识actions


网络请求-axios库

axios请求
import axios from "axios";
// 发送request请求
axios
.request({
url: "",
method: "get",
})
.then((res) => {
console.log(res.data);
});
// 发送get请求
axios
.get("", {
params: {
id: 56364543,
},
})
.then((res) => {
console.log(res.data);
});
// 发送post请求
axios
.post("", {
username: "coderwhy",
password: 213231,
})
.then((res) => {
console.log(res.data);
});

常见配置选项
并发请求可直接用 Promise.all;任一失败不会自动取消其他请求。取消时可使用 AbortController 并传入 signal。

import axios from "axios";
// const baseURL = "http://xxxxxx"
// axios.defaults.baseURL = baseURL
// 接下来正常操作
// 还可以配置其他公共的配置
// axios.defaults.timeout = 10000
// axios发送多个请求
// 本质上就是promise all
axios.all([
axios.get("xxx"),
axios.get("xxx"),
]).then(res => {
console.log(res);
})
创建axios实例
import axios from "axios"
const instance = axios.create({
baseURL: "http://xxx",
timeout: 10000,
headers: {},
})
instance.get()
instance.request()
instance.post()

请求和响应拦截器
请求和响应拦截器分别返回 config 和 response,错误分支返回 rejected Promise,保证请求继续执行、错误正常传递。
import axios from "axios"
// 对实例配置拦截器
// 前面是成功回调 后面是失败回调
axios.interceptors.request.use(
(config) => config,
(error) => Promise.reject(error)
)
axios.interceptors.response.use(
(response) => response,
(error) => Promise.reject(error)
)


vue高级语法补充
Teleport 仅改变实际 DOM 位置;h 与 createVNode 不能简单视为完全相同的别名,Vue JSX 需要专用转换配置。





















VUE3实现过渡动画
Transition 用于单个元素或组件,TransitionGroup 用于带稳定 key 的列表,后者不支持 mode。JavaScript 过渡使用 css: false 时须正确调用 done。














vue2-vue3响应式原理
Vue 2 主要使用 Object.defineProperty;Vue 3 的 reactive 主要使用 Proxy,而 ref 通过 .value 的 getter/setter 跟踪。响应式与虚拟 DOM 更新不是同一层机制。











项目打包和自动化部署
Vite 工程通常以 npm run build 生成 dist;子路径部署时让 Vite base 与 Router history base 一致。客户端环境变量不能保存私密凭据。