My Vue 3 notes on templates, components, reactivity, routing, and state management.
Example setup: Supply a Vue 3 global build for HTML examples that reference vue.js, the appropriate files and dependencies for single-file components, and your own backend for sample endpoints.
MVC and MVVM architecture
MVVM is a useful model for Vue, but Vue is a progressive UI framework. Form synchronization does not change the props-down, events-up component data flow.

Basic syntax
The data option
data() returns state for each instance. Vue 3 proxies should not be conflated with Vue 2's Object.defineProperty implementation.
Reactive data interception: Vue 3 primarily uses proxies to track object property access and mutation.


<!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>
The methods option
Use regular functions for methods that need the component's 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 fundamentals
Template syntax

Text interpolation syntax.

<!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
Use trusted or properly sanitized HTML. Content is not compiled as a Vue template; do not trust arbitrary user input.

v-pre

v-cloak
Pair it with [v-cloak] { display: none; }, mainly for in-DOM templates without a build step.

v-memo for performance optimization (3.2+)
The v-memo dependency array controls subtree updates. This example lists only name, so changes to age or height alone may not appear; include all displayed dependencies when required.
<!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: attribute binding

Binding basic attributes

<!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>
Binding 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>
Binding 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>
Dynamic attribute arguments

Binding an attribute object

<!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>
Event binding
v-on


Basic v-on usage

<!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>
Passing event arguments

<!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>
Event modifiers
.stop stops propagation and .prevent prevents default behavior. Order matters; do not combine .passive with .prevent.

stopPropagation stops event propagation.
Event modifiers invoke common event operations declaratively.
Conditional rendering

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>
In a Vue template, use template with directives such as v-if to group multiple nodes.
A div creates a real DOM wrapper.
That template group does not add a wrapper; this is not a general description of every HTML template element.
Here it provides logical grouping.

v-show

Differences between v-if and v-show
v-if creates or destroys a subtree; v-show toggles display and does not support template.

v-for

Basic v-for usage
Vue template v-for syntax accepts either in or of as its separator.
This equivalence concerns template syntax only; JavaScript for...in and for...of are different.



Detecting array updates

Reactive arrays still support ordinary JavaScript array methods.
For non-mutating methods such as filter and map, assign the result to reactive state. Whether watch runs depends on its source and options.
<!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>
The role of key in v-for
Use stable, unique keys. Avoid array indexes for reordered or stateful lists; put a template v-for key on the 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
A VNode is a JavaScript object that describes a node.










Options API

Computed properties
Computed values are cached by reactive dependencies. Keep getters free of side effects; methods run on each call and can take arguments.





<!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 properties cache results across repeated reads.
No recalculation is needed until a reactive dependency changes.
Read the property without call parentheses; caching does not make every use faster than a method.


Computed getters and setters
The getter and setter define separate reading and writing rules; the empty setter in this example does not update the name.


<!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>
The watch option
Object spread is a shallow copy, not a deep snapshot. toRaw returns the original object; mutating it should not drive reactive updates.

<!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>

Watcher configuration
Nested changes may leave old and new values referencing the same object. immediate runs the callback immediately; use flush: post or nextTick for updated DOM.




<!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>
Complete example
Bind a unique list identifier with :key and keep cart quantities at zero or above.

<!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
},
]
Forms with v-model
Basic v-model usage


<!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 with 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 with checkboxes

<!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 with radio buttons

<!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 with 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>
Binding option values

Values can come dynamically from the server rather than being hard-coded.
Use v-for together with v-bind.
v-model modifiers
.lazy uses change, .trim removes outer whitespace, and .number attempts conversion. Empty input may still be a string; validation is still required.



<!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>

Component fundamentals and scaffolding
Basic concepts




Component registration

Registering global components


<!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>
Component names

Registering local components


<!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>
Ways of developing with Vue





Using Vue CLI
Vue CLI is in maintenance mode. Use create-vue with Vite for new projects.
npm i -g @vue/cli
vue create my-project
vue create my-project --packageManager pnpm
npm -g update




Communication between components
Nested components


Component communication


Parent-to-child props: array and object syntax
Object and array defaults normally need factories. Props are shallow readonly; keep mutations explicit.
<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>






Fallthrough attributes
Undeclared attributes and listeners are in $attrs. Single-root components normally forward them; multiple roots need an explicit destination.


Child-to-parent events with 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>


Validating custom event arguments
A failed emits validator warns in development but does not stop emission. Reject invalid operations before emit; component events do not bubble.


Slots and communication beyond parent-child relationships

Basic slot usage
<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>




Named slots
<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>

Dynamic slot names
<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>

The named slot shorthand #header

Render scope
Parent-authored slot content uses parent scope; expose child data explicitly through slot props.


Scoped slots
<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>




Communication beyond parent-child relationships
provide/inject passes subtree dependencies, while Pinia manages shared business state. They can coexist.

Global event buses
Vue 3 removed instance $on, $off, and $once. External event buses require explicit subscription cleanup.



provide and inject: dependency injection
Provide a ref or computed to preserve reactivity; passing a plain current value does not synchronize future changes. A computed getter must return its result.



<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>

Additional component topics
Lifecycle hooks
Register hooks synchronously in setup. Access template DOM after mounting and clean up listeners, timers, and pending requests on unmount.




mounted: access the DOM after mounting.
unmounted: release resources and remove event listeners.
Component $refs and DOM access
Refs may be null before mounting or after v-if removes an element. Await nextTick for updated DOM; script setup components expose intended methods with 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>


Dynamic components
<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>




KeepAlive
include/exclude match component names and max limits the cache. Cached components are deactivated, not immediately unmounted; manage resources on activation and deactivation.
<!-- 状态会丢失 例如计数器等等 -->
<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>



Code splitting with webpack

Async components in Vue
defineAsyncComponent wraps async components and dynamic import enables splitting. Lazy routes use component: () => import(...) directly.
<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>


Component v-model
The modelValue plus update:modelValue contract works in Vue 3. Vue 3.4+ offers defineModel as shorthand.
<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>



Mixins
Options API still supports mixins. Composables make dependencies and returned values explicit and reduce naming collisions.
<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



The setup function
setup does not use component this. Regular setup returns template bindings; script setup requires Vue 3.2+ and exposes top-level bindings automatically.

Updating state

<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: object state
reactive supports objects, arrays, Maps, and Sets, not primitives. Use a ref for whole-value replacement and keep proxy references stable.

ref: primitive and object values
Refs hold primitives, objects, or arrays. JavaScript uses .value; top-level template refs are usually unwrapped.


One-way data flow in Vue
Props follow one-way data flow and are shallow readonly; nested mutation should not obscure state ownership.
Data flows from parent to child through props.
Children should not reassign their props.
Request changes through emitted events and let the parent update its own state.
This keeps ownership clear and makes updates easier to trace.
Using readonly
readonly creates a readonly view, while the original owner can still update writable state; it does not freeze the data source.



Inspecting reactive values

toRefs and toRef
Ordinary destructuring disconnects primitive properties; toRef/toRefs retain the link. toFixed returns a string; convert it with Number when a numeric result is needed.
<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>




Other utilities


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>

Template refs in setup
<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>

Lifecycle hooks
onBeforeUnmount runs before a component unmounts. Vue 3.5+ also provides useTemplateRef for template refs.
onBeforeMount
onMounted
onBeforeUpdate
onUpdated
onBeforeUnmount
....



provide and inject: dependency injection
Dependency injection is useful for themes and form context and can work alongside Pinia.


watch and watchEffect
watch has explicit sources; watchEffect runs immediately and tracks synchronous reads before the first await. Do not call stopWatch during its first synchronous run before initialization. Requests also need cleanup.
<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>






Composable practice



script setup syntax
defineProps, defineEmits, and defineExpose are compiler macros and need no import. Use defineExpose to expose methods such as infoBtnClick. Vue 3.5+ reactive props destructuring differs from ordinary reactive destructuring.



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

















Vue Router
The evolution of frontend routing





Introducing Vue Router
Register the router and create referenced views. Vue Router 4 supports Vue 3.
<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>



Default routes
A default nested child uses an empty path. HTML5 history deployment requires a server fallback for application routes.


RouterLink properties

Lazy route loading


Other route properties

Dynamic route matching
Parameter changes may reuse a component. Watch the relevant route.params or use an update guard rather than assuming remounting.




Nested routes


Programmatic navigation
Use named routes with params; params are not automatically incorporated when path is supplied. push adds history; replace replaces it.



Moving through browser history

Managing routes dynamically

Removing dynamic routes

Route navigation guards.


Navigation guard resolution order
The order is leave guards, beforeEach, update guards, beforeEnter, async components, beforeRouteEnter, beforeResolve, confirmation, afterEach, and DOM updates. Client token checks do not replace backend authorization.

State management with Vuex
Vuex 4 supports Vue 3; new applications can use Pinia. Mutations are synchronous; actions handle async work.




Installing Vuex

Creating a store
This store uses modules.home without namespaced, so mutation/getter names remain global. /api/example needs a backend implementation.
<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')


A single state tree


Mapping state with 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>

Basic getter usage
Getters derive and return values from state; avoid mutating state inside them.
Read getters through store.getters, including the module prefix for namespaced modules.



The mapGetters helper

Basic mutation usage


Mutation type constants

The mapMutations helper


Basic action usage



Async actions

Store modules


Namespaced modules
With namespaced: true, commit, dispatch, and getters need module prefixes; mapping helpers can take a module name.


State management with Pinia



Stores
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

Updating and resetting state
Pinia allows direct changes or $patch. Option Stores have $reset; Setup Stores implement it. Assigning $state applies a patch rather than replacing the reactive object.


Defining getters
Use storeToRefs for state and getters; actions can be destructured directly. TypeScript getters that use this need explicit return types.



Defining actions


HTTP requests with Axios

Axios requests
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);
});

Common configuration options
Use Promise.all for concurrency; one rejection does not cancel other requests. Pass an AbortController signal when cancellation is needed.

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);
})
Creating an Axios instance
import axios from "axios"
const instance = axios.create({
baseURL: "http://xxx",
timeout: 10000,
headers: {},
})
instance.get()
instance.request()
instance.post()

Request and response interceptors
Request and response interceptors return config and response respectively. Error callbacks return rejected promises so requests continue and errors propagate.
import axios from "axios"
// 对实例配置拦截器
// 前面是成功回调 后面是失败回调
axios.interceptors.request.use(
(config) => config,
(error) => Promise.reject(error)
)
axios.interceptors.response.use(
(response) => response,
(error) => Promise.reject(error)
)


Additional advanced Vue syntax
Teleport changes physical DOM placement; h and createVNode are not identical aliases, and Vue JSX needs its own transform.





















Transitions and animation in Vue 3
Transition handles one element/component; TransitionGroup handles keyed lists and has no mode. JavaScript transitions with css: false must call done appropriately.














Reactivity in Vue 2 and Vue 3
Vue 2 mainly uses Object.defineProperty. Vue 3 reactive uses proxies, while refs track through .value accessors. Reactivity and virtual DOM updates are different layers.











Builds and automated deployment
Vite typically builds dist with npm run build; align the Vite and router bases for subpaths. Do not put secrets in client environment variables.