Vue 3 のテンプレート、コンポーネント、リアクティブ API、ルーティング、状態管理の学習メモ。
実行環境:HTML の vue.js には Vue 3 のグローバルビルド、単一ファイルコンポーネントには対応するファイルと依存、例の API には独自のバックエンドが必要です。
MVC と MVVM のアーキテクチャ
MVVM は Vue を理解する手掛かりですが、Vue は UI フレームワークです。フォームの同期と、props を下へ・イベントを上へ渡す流れは別です。

基本構文
data オプション
data() はインスタンスごとの状態を返します。Vue 3 の Proxy と 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+)
配列がサブツリーの更新条件になります。例は 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>
イベントへの引数の受け渡し

<!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>
イベント修飾子
.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 の両方を使えます。
これはテンプレート構文での話です。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 と methods
算出プロパティは繰り返しの参照で結果をキャッシュします。
依存が変わるまで再計算は不要です。
括弧なしで参照しますが、常にメソッドより速いという意味ではありません。


computed の getter と setter
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>

ウォッチャーの設定
内部変更では新旧の値が同じ参照になる場合があります。更新後の 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>

textarea と 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">
<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

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

<!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>
select と 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">
<!-- 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-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>






props 以外の属性の継承
未宣言の属性・リスナーは $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 前に拒否し、コンポーネントのイベントはバブリングしない点にも注意します。


スロットと親子以外のコンポーネント通信

スロットの基本的な使い方
<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 の参照
参照はマウント前や要素削除後に null になり得ます。更新後の DOM は nextTick を待ち、公開メソッドは 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>




KeepAlive
include/exclude はコンポーネント名で照合します。キャッシュ中の停止・再開は 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 を引き続き使えます。新しいロジックではコンポーザブルで依存と戻り値を明確にできます。
<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



setup 関数
setup はコンポーネントの this を使いません。通常の setup はバインディングを返し、Vue 3.2+ の script setup では自動公開されます。

状態の変更

<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:オブジェクトの状態
reactive はオブジェクト・配列・Map・Set などに対応します。全体の置き換えには ref を検討し、代理の参照を維持します。

ref:プリミティブとオブジェクトの値
ref はプリミティブだけでなくオブジェクトや配列も保持できます。JavaScript では .value、テンプレートでは通常自動アンラップされます。


Vue の一方向データフロー
一方向のデータフローが正しい用語です。props は浅い読み取り専用で、内部変更で状態の責任を曖昧にしないようにします。
データは props を通じて親から子へ流れます。
子は props 自体を再代入しません。
変更はイベントで親へ依頼し、親が自身の状態を更新します。
状態の責任が明確になり、更新を追跡しやすくなります。
readonly の使い方
readonly は読み取り専用のビューであり、元の所有者による可変状態の更新まで禁止するものではありません。



リアクティブな値の判定

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 内のテンプレート参照
<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
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>






コンポーザブルの練習



script 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 に戻す設定が必要です。


RouterLink のプロパティ

ルートの遅延読み込み


その他のルートプロパティ

動的ルートのマッチング
パラメーターだけの変更では再利用される場合があります。route.params を監視するか更新ガードを使います。




ルートのネスト


プログラムによるナビゲーション
params には名前付きルートを使い、path だけでは自動挿入されない点に注意します。push は履歴追加、replace は置き換えです。



履歴の前後への移動

ルートの動的管理

動的ルートの削除

ルートのナビゲーションガード。


ナビゲーションガードの実行順序
離脱ガード、beforeEach、更新ガード、beforeEnter、非同期コンポーネント、beforeRouteEnter、beforeResolve、確定、afterEach、DOM 更新の順です。サーバーの認可は別途必要です。

Vuex による状態管理
Vuex 4 は Vue 3 に対応し、新規開発には Pinia が推奨されています。mutation は同期、非同期処理は action で扱います。




Vuex のインストール

store の作成
modules.home は namespaced なしのため、mutation/getter の名前はグローバルです。/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 内では state を変更しないようにします。
getter は store.getters で読み、名前空間を使う場合はモジュール名も付けます。



mapGetters ヘルパー

mutation の基本的な使い方


mutation 名の定数化

mapMutations ヘルパー


actions の基本的な使い方



actions の非同期処理

store のモジュール


名前空間付きモジュール
namespaced: true では commit・dispatch・getter にモジュール名を付け、マッピングヘルパーにも指定できます。


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 の変更とリセット
直接変更や $patch が使えます。Option Store には $reset があり、Setup Store は自作します。$state 代入も実際は patch です。


getters の定義
state/getters の分割代入には storeToRefs を使います。action は直接分割でき、this を使う TypeScript getter には戻り値の型が必要です。



actions の定義


Axios による HTTP 通信

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 を使えますが、1 件の失敗で他は中止されません。中止には 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 は完全な別名ではなく、JSX は専用設定が必要です。





















Vue 3 のトランジションとアニメーション
Transition は単一要素、TransitionGroup は key 付きリスト用で mode は使えません。css: false の JavaScript 遷移では done を適切に呼びます。














Vue 2 と Vue 3 のリアクティビティの仕組み
Vue 2 は主に Object.defineProperty、Vue 3 の reactive は Proxy、ref は .value のアクセサーを使います。仮想 DOM とは異なる層です。











ビルドと自動デプロイ
Vite では通常 npm run build で dist を生成し、サブパスでは Vite とルーターの base を揃えます。秘密情報はクライアントへ渡しません。