logo头像
Snippet 博客主题

vue3快速上手

一、 Vue3简介

1.1、性能的提升

  • 打包大小减少41%

  • 初次渲染快55%, 更新渲染快133%

  • 内存减少54%

1.2、源码的升级

  • 使用Proxy代替defineProperty实现响应式。

  • 重写虚拟DOM的实现和Tree-Shaking

1.3、拥抱TypeScript

  • Vue3可以更好的支持TypeScript

1.4、新的特性

  1. Composition API(组合API):

    • setup

    • refreactive

    • computedwatch

      ……

  2. 新的内置组件:

    • Fragment

    • Teleport

    • Suspense

      ……

  3. 其他改变:

    • 新的生命周期钩子

    • data 选项应始终被声明为一个函数

    • 移除keyCode支持作为 v-on 的修饰符

      ……


二、创建Vue3工程

2.1、基于 vue-cli 创建

点击查看官方文档

备注:目前vue-cli已处于维护模式,官方推荐基于 Vite 创建项目。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version

## 安装或者升级你的@vue/cli
npm install -g @vue/cli

## 执行创建命令
vue create vue_test

## 随后选择3.x
## Choose a version of Vue.js that you want to start the project with (Use arrow keys)
## > 3.x
## 2.x

## 启动
cd vue_test
npm run serve

2.2、基于 vite 创建(推荐)

vite 是新一代前端构建工具,官网地址:https://vitejs.cnvite的优势如下:

  • 轻量快速的热重载(HMR),能实现极速的服务启动。
  • TypeScriptJSXCSS 等支持开箱即用。
  • 真正的按需编译,不再等待整个应用编译完成。
  • webpack构建 与 vite构建对比图如下:

webpack构建 vite构建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
## 1.创建命令
npm create vue@latest

## 2.具体配置
## 配置项目名称
√ Project name: vue3_test
## 是否添加TypeScript支持
√ Add TypeScript? Yes
## 是否添加JSX支持
√ Add JSX Support? No
## 是否添加路由环境
√ Add Vue Router for Single Page Application development? No
## 是否添加pinia环境
√ Add Pinia for state management? No
## 是否添加单元测试
√ Add Vitest for Unit Testing? No
## 是否添加端到端测试方案
√ Add an End-to-End Testing Solution? » No
## 是否添加ESLint语法检查
√ Add ESLint for code quality? Yes
## 是否添加Prettiert代码格式化
√ Add Prettier for code formatting? No

自己动手编写一个App组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<div class="app">
<h1>你好啊!</h1>
</div>
</template>

<script lang="ts">
export default {
name: 'App', // 组件名
}
</script>

<style>
.app {
padding: 20px;
background-color: #ddd;
border-radius: 10px;
box-shadow: 0 0 10px;
}
</style>

安装官方推荐的vscode插件:

image-20240515230813598

总结:

  • Vite 项目中,index.html 是项目的入口文件,在项目最外层。
  • 加载index.html后,Vite 解析 <script type="module" src="xxx"> 指向的JavaScript
  • Vue3**中是通过 **createApp 函数创建一个应用实例。

2.3、一个简单的效果

Vue3向下兼容Vue2语法,且Vue3中的模板中可以没有根标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<template>
<div class="person">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="changeName">
修改名字
</button>
<button @click="changeAge">
年龄+1
</button>
<button @click="showTel">
点我查看联系方式
</button>
</div>
</template>

<script lang="ts">
export default {
name: 'App',
data() {
return {
name: '张三',
age: 18,
tel: '13888888888',
}
},
methods: {
changeName() {
this.name = 'zhang-san'
},
changeAge() {
this.age += 1
},
showTel() {
alert(this.tel)
},
},
}
</script>

三、Vue3核心语法

3.1、OptionsAPI 与 CompositionAPI

  • Vue2API设计是Options(配置)风格的。
  • Vue3API设计是Composition(组合)风格的。

1)、Options API 的弊端

Options类型的 API,数据、方法、计算属性等,是分散在:datamethodscomputed中的,若想新增或者修改一个需求,就需要分别修改:datamethodscomputed,不便于维护和复用。

1.gif2.gif


2)、Composition API 的优势

可以用函数的方式,更加优雅的组织代码,让相关功能的代码更加有序的组织在一起。

3.gif4.gif

说明:以上四张动图原创作者:大帅老猿


3.2、拉开序幕的 setup

1)、setup 概述

setupVue3中一个新的配置项,值是一个函数,它是 Composition API “表演的舞台,组件中所用到的:数据、方法、计算属性、监视……等等,均配置在setup中。

特点如下:

  • setup函数返回的对象中的内容,可直接在模板中使用。
  • setup中访问thisundefined
  • setup 函数会在beforeCreate之前调用,它是“领先”所有钩子执行的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<template>
<div class="person">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="changeName">
修改名字
</button>
<button @click="changeAge">
年龄+1
</button>
<button @click="showTel">
点我查看联系方式
</button>
</div>
</template>

<script lang="ts">
export default {
name: 'Person',
setup() {
// 数据,原来写在data中(注意:此时的name、age、tel数据都不是响应式数据)
let name = '张三'
let age = 18
const tel = '13888888888'

// 方法,原来写在methods中
function changeName() {
name = 'zhang-san' // 注意:此时这么修改name页面是不变化的
console.log(name)
}
function changeAge() {
age += 1 // 注意:此时这么修改age页面是不变化的
console.log(age)
}
function showTel() {
alert(tel)
}

// 返回一个对象,对象中的内容,模板中可以直接使用
return { name, age, tel, changeName, changeAge, showTel }
},
}
</script>


2)、setup 的返回值

  • 若返回一个对象:则对象中的:属性、方法等,在模板中均可以直接使用**(重点关注)。**
  • 若返回一个函数:则可以自定义渲染内容将直接渲染在页面,代码如下:
1
2
3
setup(){
return ()=> '你好啊!'
}

3)、setup 与 Options API 的关系

  • Vue2 的配置(datamethos……)中可以访问到 setup中的属性、方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <template>
    <h2>姓名:{{ c }}</h2>
    </template>

    <script lang="ts">
    export default {
    name: 'Person',
    setup() {
    const name = '张三'
    return { name }
    },
    data() {
    return {
    c: this.name,
    }
    },
    }
    </script>
  • 但在setup不能访问到Vue2的配置(datamethos……)。

  • 如果与Vue2冲突,则setup优先。


4)、setup 语法糖

setup函数有一个语法糖,这个语法糖,可以让我们把setup独立出去(默认会把里面的数据return出去),代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<template>
<div class="person">
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="changName">修改名字</button>
<button @click="changAge">年龄+1</button>
<button @click="showTel">点我查看联系方式</button>
</div>
</template>

<script lang="ts">
export default {
name:'Person',
}
</script>

<!-- 下面的写法是setup语法糖 -->
<script setup lang="ts">
console.log(this) //undefined

// 数据(注意:此时的name、age、tel都不是响应式数据)
let name = '张三'
let age = 18
let tel = '13888888888'

// 方法
function changName(){
name = '李四'//注意:此时这么修改name页面是不变化的
}
function changAge(){
console.log(age)
age += 1 //注意:此时这么修改age页面是不变化的
}
function showTel(){
alert(tel)
}
</script>

**扩展:**上述代码,还需要编写一个不写setupscript标签,去指定组件名字,比较麻烦,我们可以借助vite中的插件简化

  1. 第一步:npm i vite-plugin-vue-setup-extend -D
  2. 第二步:vite.config.ts
1
2
3
4
5
6
import { defineConfig } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'

export default defineConfig({
plugins: [ VueSetupExtend() ]
})
  1. 第三步:
1
<script setup lang="ts" name="Person"></script>

3.3、ref 创建:基本类型的响应式数据

  • **作用:**定义响应式变量。
  • 语法:let xxx = ref(初始值)
  • **返回值:**一个RefImpl的实例对象,简称ref对象refref对象的value属性是响应式的
  • 注意点:
    • JS中操作数据需要:xxx.value,但模板中不需要.value,直接使用即可。
    • 对于let name = ref('张三')来说,name不是响应式的,name.value是响应式的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<template>
<div class="person">
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">年龄+1</button>
<button @click="showTel">点我查看联系方式</button>
</div>
</template>

<script setup lang="ts" name="Person">
import {ref} from 'vue'
// name和age是一个RefImpl的实例对象,简称ref对象,它们的value属性是响应式的。
let name = ref('张三')
let age = ref(18)
// tel就是一个普通的字符串,不是响应式的
let tel = '13888888888'

function changeName(){
// JS中操作ref对象时候需要.value
name.value = '李四'
console.log(name.value)

// 注意:name不是响应式的,name.value是响应式的,所以如下代码并不会引起页面的更新。
// name = ref('zhang-san')
}
function changeAge(){
// JS中操作ref对象时候需要.value
age.value += 1
console.log(age.value)
}
function showTel(){
alert(tel)
}
</script>

3.4、reactive 创建:对象类型的响应式数据

  • 作用:定义一个响应式对象(基本类型不要用它,要用ref,否则报错)
  • 语法:let 响应式对象= reactive(源对象)
  • **返回值:**一个Proxy的实例对象,简称:响应式对象。
  • 注意点:reactive定义的响应式数据是“深层次”的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<template>
<div class="person">
<h2>汽车信息:一台{{ car.brand }}汽车,价值{{ car.price }}万</h2>
<h2>游戏列表:</h2>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
<h2>测试:{{obj.a.b.c.d}}</h2>
<button @click="changeCarPrice">修改汽车价格</button>
<button @click="changeFirstGame">修改第一游戏</button>
<button @click="test">测试</button>
</div>
</template>

<script lang="ts" setup name="Person">
import { reactive } from 'vue'

// 数据
let car = reactive({ brand: '奔驰', price: 100 })
let games = reactive([
{ id: 'ahsgdyfa01', name: '英雄联盟' },
{ id: 'ahsgdyfa02', name: '王者荣耀' },
{ id: 'ahsgdyfa03', name: '原神' }
])
let obj = reactive({
a:{
b:{
c:{
d:666
}
}
}
})

function changeCarPrice() {
car.price += 10
}
function changeFirstGame() {
games[0].name = '流星蝴蝶剑'
}
function test(){
obj.a.b.c.d = 999
}
</script>

3.5、ref 创建:对象类型的响应式数据

  • 其实ref接收的数据可以是:基本类型对象类型
  • ref接收的是对象类型,内部其实也是调用了reactive函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<template>
<div class="person">
<h2>汽车信息:一台{{ car.brand }}汽车,价值{{ car.price }}万</h2>
<h2>游戏列表:</h2>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
<h2>测试:{{obj.a.b.c.d}}</h2>
<button @click="changeCarPrice">修改汽车价格</button>
<button @click="changeFirstGame">修改第一游戏</button>
<button @click="test">测试</button>
</div>
</template>

<script lang="ts" setup name="Person">
import { ref } from 'vue'

// 数据
let car = ref({ brand: '奔驰', price: 100 })
let games = ref([
{ id: 'ahsgdyfa01', name: '英雄联盟' },
{ id: 'ahsgdyfa02', name: '王者荣耀' },
{ id: 'ahsgdyfa03', name: '原神' }
])
let obj = ref({
a:{
b:{
c:{
d:666
}
}
}
})

console.log(car)

function changeCarPrice() {
car.value.price += 10
}
function changeFirstGame() {
games.value[0].name = '流星蝴蝶剑'
}
function test(){
obj.value.a.b.c.d = 999
}
</script>

3.6、ref 对比 reactive

宏观角度看:

  1. ref用来定义:基本类型数据对象类型数据

  2. reactive用来定义:对象类型数据

  • 区别:
  1. ref创建的变量必须使用.value(可以使用Vue - Official插件自动添加.value)。

    自动补充value
  2. reactive重新分配一个新对象,会失去响应式(可以使用Object.assign去整体替换)。

  • 使用原则:
  1. 若需要一个基本类型的响应式数据,必须使用ref
  2. 若需要一个响应式对象,层级不深,refreactive都可以。
  3. 若需要一个响应式对象,且层级较深,推荐使用reactive

3.7、toRefs 与 toRef

从一个响应式对象中解构对象,解构出来的属性必丢失响应,因此需要使用到toRefs 与 toRef

例如:let route = useRoute()
let { query } = route // 这里的query响应必定会丢失
修改:let { query } = toRefs(route)

  • 作用:将一个响应式对象中的每一个属性,转换为ref对象(响应式)。
  • 备注:toRefstoRef功能一致,但toRefs可以批量转换。
  • 语法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<template>
<div class="person">
<h2>姓名:{{person.name}}</h2>
<h2>年龄:{{person.age}}</h2>
<h2>性别:{{person.gender}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="changeGender">修改性别</button>
</div>
</template>

<script lang="ts" setup name="Person">
import {ref,reactive,toRefs,toRef} from 'vue'

// 数据
let person = reactive({name:'张三', age:18, gender:'男'})

// 通过toRefs将person对象中的n个属性批量取出,且依然保持响应式的能力
let {name,gender} = toRefs(person) // 将person中的属性名对应的属性值都转变成ref对象

// 通过toRef将person对象中的age属性取出,且依然保持响应式的能力
let age = toRef(person,'age')

// 方法
function changeName(){
name.value += '~' // 因为转换成了ref对象,所以用.value赋值
}
function changeAge(){
age.value += 1
}
function changeGender(){
gender.value = '女'
}
</script>

3.8、computed

作用:根据已有数据计算出新数据(和Vue2中的computed作用一致)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
<div class="person">
姓:<input type="text" v-model="firstName"> <br>
名:<input type="text" v-model="lastName"> <br>
全名:<span>{{fullName}}</span> <br>
<button @click="changeFullName">全名改为:li-si</button>
</div>
</template>

<script setup lang="ts" name="App">
import {ref,computed} from 'vue'

let firstName = ref('zhang')
let lastName = ref('san')

// 计算属性——只读取,不修改
/* let fullName = computed(()=>{
return firstName.value + '-' + lastName.value
}) */

/* function changeFullName() {
fullName.value = 'li-si'; // 报错:无法为“value”赋值,因为它是只读属性
} */


// 计算属性——既读取又修改
let fullName = computed({
// 读取
get(){
return firstName.value + '-' + lastName.value
},
// 修改
set(newVal){
console.log('有人修改了fullName',val)
firstName.value = newVal.split('-')[0]
lastName.value = newVal.split('-')[1]
}
})

function changeFullName(){
fullName.value = 'li-si'
}
</script>

3.9、watch

  • 作用:监视数据的变化(和Vue2中的watch作用一致)
  • 特点:Vue3中的watch只能监视以下四种数据
    1. ref定义的数据。
    2. reactive定义的数据。
    3. 函数返回一个值(getter函数)。
    4. 一个包含上述内容的数组。

我们在Vue3中使用watch的时候,通常会遇到以下几种情况:

1)、情况一:监视ref定义的基本类型数据

监视ref定义的【基本类型】数据:直接写数据名即可,监视的是其value值的改变。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div class="person">
<h1>情况一:监视【ref】定义的【基本类型】数据</h1>
<h2>当前求和为:{{ sum }}</h2>
<button @click="changeSum">
点我sum+1
</button>
</div>
</template>

<script lang="ts" setup name="Person">
import { ref, watch } from 'vue'
// 数据
const sum = ref(0)
// 方法
function changeSum() {
sum.value += 1
}
// 监视,情况一:监视【ref】定义的【基本类型】数据
const stopWatch = watch(sum, (newValue, oldValue) => {
console.log('sum变化了', newValue, oldValue)
if (newValue >= 10) {
// 当值大于等于10的时候就停止监听
stopWatch()
}
})
</script>

2)、情况二:监视ref定义的对象类型数据

监视ref定义的【对象类型】数据:直接写数据名,监视的是对象的【地址值】,若想监视对象内部的数据,要手动开启深度监视。

注意:

  • 若修改的是ref定义的对象中的属性,newValueoldValue 都是新值,因为它们是同一个对象。

  • 若修改整个ref定义的对象,newValue 是新值, oldValue 是旧值,因为不是同一个对象了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<template>
<div class="person">
<h1>情况二:监视【ref】定义的【对象类型】数据</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<button @click="changeName">
修改名字
</button>
<button @click="changeAge">
修改年龄
</button>
<button @click="changePerson">
修改整个人
</button>
</div>
</template>

<script lang="ts" setup name="Person">
import { ref, watch } from 'vue'
// 数据
const person = ref({
name: '张三',
age: 18,
})
// 方法
function changeName() {
person.value.name += '~'
}
function changeAge() {
person.value.age += 1
}
function changePerson() {
person.value = { name: '李四', age: 90 }
}
/*
watch的第一个参数是:被监视的数据
watch的第二个参数是:监视的回调
watch的第三个参数是:配置对象(deep、immediate等等.....)
*/

// 这里有几个问题需要注意:
// 1、监视【ref】定义的【对象类型】数据,监视的是对象的地址值(整个对象变化才会触发监听)
// 调用changeName和changeAge方法不会触发这个监听,changePerson则会触发
watch(person, (newValue, oldValue) => {
console.log('person变化了', newValue, oldValue)
})

// 2、若想监视对象内部属性的变化,需要手动开启深度监视
// 调用changeName、changeAge、changePerson方法都会会触发这个监听
// 调用changeName、changeAge监听某属性值的变化,新值和旧值都是一样的,因为这里没有改变对象的地址值,导致指向的都是同一个地址(reactive定义的对象也一样)。changePerson是对person赋予一个新的对象,引用地址改变了因此新值和旧值才会不一样
watch(person, (newValue, oldValue) => {
console.log('person变化了', newValue, oldValue)
}, { deep: true, immediate: true })
</script>

3)、情况三:监视reactive定义的对象类型数据

监视reactive定义的【对象类型】数据,且默认开启了深度监视。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<template>
<div class="person">
<h1>情况三:监视【reactive】定义的【对象类型】数据</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<button @click="changeName">
修改名字
</button>
<button @click="changeAge">
修改年龄
</button>
<button @click="changePerson">
修改整个人
</button>
<hr>
<h2>测试:{{ obj.a.b.c }}</h2>
<button @click="test">
修改obj.a.b.c
</button>
</div>
</template>

<script lang="ts" setup name="Person">
import { reactive, watch } from 'vue'
// 数据
const person = reactive({
name: '张三',
age: 18,
})
const obj = reactive({
a: {
b: {
c: 666,
},
},
})
// 方法
function changeName() {
person.name += '~'
}
function changeAge() {
person.age += 1
}
function changePerson() {
Object.assign(person, { name: '李四', age: 80 })
}
function test() {
obj.a.b.c = 888
}

// 监视,情况三:监视【reactive】定义的【对象类型】数据,且默认是开启深度监视的
// changeName、hangeAge这里改变的对象里面的属性值,对象的引用地址没改变因此新值和旧值都是一样, changePerson中由于是reactive定义的响应式对象不能直接赋值,需要使用Object.assign()给源对象添加可枚 举属性,因为是给原对象添加可枚举属性,所以可知原对象的引用地址没变,因此新值和旧值也是一样的。
watch(person, (newValue, oldValue) => {
console.log('person变化了', newValue, oldValue)
})
watch(obj, (newValue, oldValue) => {
console.log('Obj变化了', newValue, oldValue)
})
</script>

4)、情况四:监视ref/reactive定义的对象类型数据中的某个属性

监视refreactive定义的【对象类型】数据中的某个属性,注意点如下:

  1. 若该属性值不是【对象类型】,需要写成函数形式。
  2. 若该属性值是依然是【对象类型】,可直接编,也可写成函数,建议写成函数。

结论:监视的要是对象里的属性,那么最好写函数式

注意点:若是对象监视的是地址值,需要关注对象内部,需要手动开启深度监视。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<template>
<div class="person">
<h1>情况四:监视【ref】或【reactive】定义的【对象类型】数据中的某个属性</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<h2>汽车:{{ person.car.c1 }}、{{ person.car.c2 }}</h2>
<button @click="changeName">
修改名字
</button>
<button @click="changeAge">
修改年龄
</button>
<button @click="changeC1">
修改第一台车
</button>
<button @click="changeC2">
修改第二台车
</button>
<button @click="changeCar">
修改整个车
</button>
</div>
</template>

<script lang="ts" setup name="Person">
import { reactive, watch } from 'vue'

// 数据
const person = reactive({
name: '张三',
age: 18,
car: {
c1: '奔驰',
c2: '宝马',
},
})
// 方法
function changeName() {
person.name += '~'
}
function changeAge() {
person.age += 1
}
function changeC1() {
person.car.c1 = '奥迪'
}
function changeC2() {
person.car.c2 = '大众'
}
function changeCar() {
person.car = { c1: '雅迪', c2: '爱玛' }
}

// 监视,情况四:监视响应式对象中的某个属性,且该属性是对象类型的,可以直接写,也能写函数,更推荐写函数
// 这里有几个问题需要注意:
// 1、监视响应式对象中的某个属性,且该属性是基本类型的,要写成函数式
watch(() => person.name, (newValue, oldValue) => {
console.log('person.name变化了', newValue, oldValue)
})
// 2、监视响应式对象中的某个属性,且该属性是对象类型的
// 2-1、直接写监听的属性对象person.car(不推荐),当改变整个car对象不会触发监听,当改变car对象中的某个属性则会触发监听。
watch(person.car, (newValue, oldValue) => {
console.log('person.car变化了', newValue, oldValue)
})
// 2-2、直接写监听的属性为一个有返回值的函数() => person.car 推荐,当改变整个car对象会触发监听,当改变car对象中的某个属性则不会触发监听,需开启深度监听。
watch(() => person.car, (newValue, oldValue) => {
console.log('person.car变化了', newValue, oldValue)
}, { deep: true })
</script>

5)、情况五:监视上述的多个数据

监视上述的多个数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<template>
<div class="person">
<h1>情况五:监视上述的多个数据</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<h2>汽车:{{ person.car.c1 }}、{{ person.car.c2 }}</h2>
<button @click="changeName">
修改名字
</button>
<button @click="changeAge">
修改年龄
</button>
<button @click="changeC1">
修改第一台车
</button>
<button @click="changeC2">
修改第二台车
</button>
<button @click="changeCar">
修改整个车
</button>
</div>
</template>

<script lang="ts" setup name="Person">
import { reactive, watch } from 'vue'

// 数据
const person = reactive({
name: '张三',
age: 18,
car: {
c1: '奔驰',
c2: '宝马',
},
})
// 方法
function changeName() {
person.name += '~'
}
function changeAge() {
person.age += 1
}
function changeC1() {
person.car.c1 = '奥迪'
}
function changeC2() {
person.car.c2 = '大众'
}
function changeCar() {
person.car = { c1: '雅迪', c2: '爱玛' }
}

// 监视,情况五:监视上述的多个数据
watch(
[() => person.name, person.car],
(newValue, oldValue) => {
console.log('person.car变化了', newValue, oldValue) // 生成的是一个数组
},
{ deep: true },
)
</script>


3.10、watchEffect

  • 官网:立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行该函数。

  • watch对比watchEffect

    1. 都能监听响应式数据的变化,不同的是监听数据变化的方式不同

    2. watch:要明确指出监视的数据

    3. watchEffect:不用明确指出监视的数据(函数中用到哪些属性,那就监视哪些属性),初始化的时候会执行一次。

  • 示例代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    <template>
    <div class="person">
    <h1>需求:水温达到50℃,或水位达到20cm,则联系服务器</h1>
    <h2 id="demo">
    水温:{{ temp }}
    </h2>
    <h2>水位:{{ height }}</h2>
    <button @click="changePrice">
    水温+1
    </button>
    <button @click="changeSum">
    水位+10
    </button>
    </div>
    </template>

    <script lang="ts" setup name="Person">
    import { ref, watch, watchEffect } from 'vue'
    // 数据
    const temp = ref(0)
    const height = ref(0)

    // 方法
    function changePrice() {
    temp.value += 10
    }
    function changeSum() {
    height.value += 1
    }

    // 用watch实现,需要明确的指出要监视:temp、height
    const stopWtach1 = watch([temp, height], (value) => {
    // 从value中获取最新的temp值、height值
    const [newTemp, newHeight] = value
    // 室温达到50℃,或水位达到20cm,立刻联系服务器
    if (newTemp >= 50 || newHeight >= 20) {
    console.log(document.getElementById('demo')?.innerText)
    console.log('联系服务器')
    }
    if (newTemp >= 100 || newHeight >= 50) {
    console.log('清理了')
    stopWtach1()
    }
    })

    // 用watchEffect实现,不用
    const stopWtach = watchEffect(() => {
    // 室温达到50℃,或水位达到20cm,立刻联系服务器
    if (temp.value >= 50 || height.value >= 20) {
    console.log(document.getElementById('demo')?.innerText)
    console.log('联系服务器')
    }
    // 水温达到100,或水位达到50,取消监视
    if (temp.value === 100 || height.value === 50) {
    console.log('清理了')
    stopWtach()
    }
    })
    </script>


3.11、标签的 ref 属性

作用:用于注册模板引用。

  • 用在普通DOM标签上,获取的是DOM节点。

  • 用在组件标签上,获取的是组件实例对象。

用在普通DOM标签上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
<div class="person">
<h1 id="guiGu" ref="title1">
尚硅谷
</h1>
<h2 ref="title2">
前端
</h2>
<h3 ref="title3">
Vue
</h3>
<br>
<br>
<button @click="showLog">
点我打印内容
</button>
</div>
</template>

<script lang="ts" setup name="Person">
import { ref } from 'vue'

const title1 = ref() // 变量命名要和ref定义的命名一致
const title2 = ref()
const title3 = ref()

function showLog() {
// 通过id获取元素
const t1 = document.getElementById('guiGu')
// 打印内容(三种ts的断言方式)
console.log((t1 as HTMLElement).innerText)
// console.log((<HTMLElement>t1).innerText);
// console.log(t1?.innerText)

/************************************/

// 通过ref获取元素
console.log(title1.value)
console.log(title2.value)
console.log(title3.value)
}
</script>

用在组件标签上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<!-- 父组件father.vue -->
<template>
<div class="index">
<h2>父组件</h2>
<button @click="updateGeGe">
更新哥哥的信息
</button>
<br>
<br>
<button @click="updateDiDi">
更新弟弟的信息
</button>
<br>
<br>
<Person ref="ren" />
<br>
<Person1 ref="ren1" />
</div>
</template>

<script lang="ts" setup name="App">
import { ref } from 'vue'
import Person1 from './Person1.vue'
import Person from './Person.vue'

const ren = ref()
const ren1 = ref()

function updateGeGe() {
ren.value.execute()
ren.value.name = '张大三'
ren.value.age = 22
}
function updateDiDi() {
ren1.value.name = '大米'
ren1.value.age = 18
}
</script>

<style>
.index {
padding: 20px;
background: rgb(255 193 170);
}
</style>


<!-- 子组件Person.vue中要使用defineExpose暴露内容 -->
<template>
<div class="gege">
<h2>哥哥组件</h2>
<div>姓名:{{ name }}</div>
<div>年龄:{{ age }}</div>
</div>
</template>

<script lang="ts" setup name="Person">
import { defineExpose, ref } from 'vue'
// 数据
const name = ref('张三')
const age = ref(18)

function execute() {
console.log('已执行哥哥组件中的方法')
}
// 使用defineExpose将组件中的数据交给外部
defineExpose({ name, age, execute })
</script>

<style>
.gege {
background: rgb(160 235 255);
}
</style>


<!-- 子组件Person1.vue中要使用defineExpose暴露内容 -->
<template>
<div class="didi">
<h2>弟弟组件</h2>
<div>姓名:{{ name }}</div>
<div>年龄:{{ age }}</div>
</div>
</template>

<script lang="ts" setup name="Person">
import { defineExpose, ref } from 'vue'
// 数据
const name = ref('小米')
const age = ref(12)

// 使用defineExpose将组件中的数据交给外部
defineExpose({ name, age })
</script>

<style>
.didi {
background: rgb(163 157 255);
}
</style>


3.12、组件的$refs 属性

获取到页面所有组件的ref实例对象

image-20240808005710611

父组件(father.vue)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<template>
<div class="index">
<h2>父组件</h2>
<button @click="update($refs)">
更新兄弟的信息
</button>
<br>
<br>
<Person ref="ren" />
<br>
<Person1 ref="ren1" />
</div>
</template>

<script lang="ts" setup name="App">
import { ref } from 'vue'
import Person1 from './index1.vue'
import Person from './index.vue'

const ren = ref()
const ren1 = ref()

function update(refs: any) {
console.log(refs)
refs.ren.name = '张大三'
refs.ren.age = 22
refs.ren.execute()
refs.ren1.name = '大米'
refs.ren1.age = 18
}
</script>

<style>
.index {
padding: 20px;
background: rgb(255 193 170);
}
</style>

子组件(Person.vue)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div class="gege">
<h2>哥哥组件</h2>
<div>姓名:{{ name }}</div>
<div>年龄:{{ age }}</div>
</div>
</template>

<script lang="ts" setup name="Person">
import { defineExpose, ref } from 'vue'
// 数据
const name = ref('张三')
const age = ref(18)

function execute() {
console.log('已执行哥哥组件中的方法')
}
// 使用defineExpose将组件中的数据交给外部
defineExpose({ name, age, execute })
</script>

<style>
.gege {
background: rgb(160 235 255);
}
</style>

子组件(Person1.vue)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
<div class="didi">
<h2>弟弟组件</h2>
<div>姓名:{{ name }}</div>
<div>年龄:{{ age }}</div>
</div>
</template>

<script lang="ts" setup name="Person">
import { defineExpose, ref } from 'vue'
// 数据
const name = ref('小米')
const age = ref(12)

// 使用defineExpose将组件中的数据交给外部
defineExpose({ name, age })
</script>

<style>
.didi {
background: rgb(163 157 255);
}
</style>


3.13、props

1
2
3
4
5
6
7
8
9
10
/ types/index.ts
// 定义一个接口,限制每个Person对象的格式
export interface PersonInter {
id:string,
name:string,
age:number
}

// 定义一个自定义类型Persons
export type Persons = Array<PersonInter>

App.vue中代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<Person :list="persons" />
</template>

<script lang="ts" setup name="App">
import type { Persons } from './types'
import { reactive } from 'vue'
import Person from './components/Person.vue'

// let persons:Persons = reactive([
const persons = reactive<Persons>([
{ id: 'e98219e12', name: '张三', age: 18 },
{ id: 'e98219e13', name: '李四', age: 19 },
{ id: 'e98219e14', name: '王五', age: 20 },
])
</script>

Person.vue中代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<template>
<div class="person">
<ul>
<li v-for="item in list" :key="item.id">
{{ item.name }}--{{ item.age }}
</li>
</ul>
</div>
</template>

<script lang="ts" setup name="Person">
import { defineProps } from 'vue'

// 第一种写法:仅接收
// let props = defineProps(['list'])

// 第二种写法:接收+限制类型,因为传来的可能不止一个数据,因此在泛型中用一个对象包裹
// let props = defineProps<{ list: Persons; aa?: string }>();

// 第三种写法:接收+限制类型+指定默认值+限制必要性
// .....withDefaults 指定默认值
// .....Persons 限制类型
// .....list?: 限制必要性 :父组件必须要 ?: 父组件可不传 ts语法

const props = withDefaults(defineProps<{ list?: Persons }>(), {
list: () => [{ id: 'asdasg01', name: '小猪佩奇', age: 18 }],
})
console.log(props)
</script>

易懂

在 Vue 3 中使用 TypeScript 时,你可以通过 withDefaults 函数来为 defineProps 定义的 props 设置默认值。withDefaults 函数允许你指定默认值,同时保持 TypeScript 的类型检查。

以下是如何在 TypeScript 中为 defineProps 设置默认值的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
假设你有一个子组件 PasswordDialog.vue,你可以这样定义和接收 lianlianMercNo,并为其设置默认值:

<template>
<div>
<!-- 使用接收到的 lianlianMercNo -->
<p>Merchant Number: {{ lianlianMercNo }}</p>
</div>
</template>

<script setup lang="ts">
import { defineProps, withDefaults } from 'vue'

// 定义 props 的类型
interface Props {
lianlianMercNo?: number // 将其设为可选
}

// 使用 withDefaults 来为 props 设置默认值
const props = withDefaults(defineProps<Props>(), {
lianlianMercNo: 1234, // 设置默认值
})
</script>

1
2
3
4
5
6
7
8
9
10
11
在父组件中,你可以这样使用这个子组件并传递 lianlianMercNo:
<template>
<div>
<PasswordDialog ref="passwordRef" lianlian-merc-no="4444" />
</div>
</template>

<script setup lang="ts">
import PasswordDialog from './PasswordDialog.vue'
</script>

在这个示例中:

子组件 PasswordDialog.vue 中定义了一个 Props 接口,其中 lianlianMercNo 属性是可选的(使用 ? 标记)。
使用 withDefaults 函数将 defineProps() 包裹起来,并为 lianlianMercNo 设置默认值 1234。
如果父组件没有传递 lianlianMercNo,则 PasswordDialog 组件会使用默认值 1234。
这样,你就可以在 TypeScript 中为 defineProps 设置默认值,同时保持类型检查。


3.14、生命周期

  • 概念:Vue组件实例在创建时要经历一系列的初始化步骤,在此过程中Vue会在合适的时机,调用特定的函数,从而让开发者有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子

  • 规律:

    生命周期整体分为四个阶段,分别是:创建、挂载、更新、销毁,每个阶段都有两个钩子,一前一后。

  • Vue2的生命周期

    创建阶段:beforeCreatecreated

    挂载阶段:beforeMountmounted

    更新阶段:beforeUpdateupdated

    销毁阶段:beforeDestroydestroyed

  • Vue3的生命周期

    创建阶段:setup

    挂载阶段:onBeforeMountonMounted

    更新阶段:onBeforeUpdateonUpdated

    卸载阶段:onBeforeUnmountonUnmounted

  • 常用的钩子:onMounted(挂载完毕)、onUpdated(更新完毕)、onBeforeUnmount(卸载之前)

  • 注意项:(重点)

    到底是子组件挂载(onMounted)先执行还是父组件的挂载(onMounted)先执行?

    答:先执行子组件的挂载再执行父组件的挂载,vue项目中app.vue是所有组件的顶级组件,因此它的挂载是最后执行

  • 示例代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    <template>
    <div class="person">
    <h2>当前求和为:{{ sum }}</h2>
    <button @click="changeSum">
    点我sum+1
    </button>
    </div>
    </template>

    <!-- vue3写法 -->
    <script lang="ts" setup name="Person">
    import {
    onBeforeMount,
    onBeforeUnmount,
    onBeforeUpdate,
    onMounted,
    onUnmounted,
    onUpdated,
    ref,
    } from 'vue'

    // 数据
    const sum = ref(0)
    // 方法
    function changeSum() {
    sum.value += 1
    }
    console.log('setup')
    // 生命周期钩子
    onBeforeMount(() => {
    console.log('挂载之前')
    })
    onMounted(() => {
    console.log('挂载完毕')
    })
    onBeforeUpdate(() => {
    console.log('更新之前')
    })
    onUpdated(() => {
    console.log('更新完毕')
    })
    onBeforeUnmount(() => {
    console.log('卸载之前')
    })
    onUnmounted(() => {
    console.log('卸载完毕')
    })
    </script>


3.15、自定义hook

接口地址:https://dog.ceo/api/breed/pembroke/images/random 随机获取一张狗的图片(有的时候须要梯子)

  • 什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装,类似于vue2.x中的mixin

  • 自定义hook的优势:复用代码, 让setup中的逻辑更清楚易懂。

  • useSum.ts和useDog.ts中的可以分别写onMounted钩子

示例代码:

  • useSum.ts中内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import {ref,onMounted} from 'vue'

    export default function(){
    let sum = ref(0)

    const increment = ()=>{
    sum.value += 1
    }
    const decrement = ()=>{
    sum.value -= 1
    }
    onMounted(()=>{
    increment()
    })

    //向外部暴露数据
    return {sum,increment,decrement}
    }
  • useDog.ts中内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    import axios from 'axios'
    import { onMounted, reactive, ref } from 'vue'

    export default function () {
    const dogList = reactive<string[]>([])
    const loading = ref(false)

    const getDog = async () => {
    loading.value = true
    try {
    const res = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')

    dogList.push(res.data.message)
    } catch (error) {
    console.log(error)
    } finally {
    loading.value = false
    }
    }

    onMounted(() => {
    getDog()
    })
    // 向外暴露数据
    return { dogList, loading, getDog }
    }
  • 组件中具体使用:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    <template>
    <h2>当前求和为:{{ sum }}</h2>
    <button @click="increment">
    点我+1
    </button>
    <button @click="decrement">
    点我-1
    </button>
    <hr>
    <img v-for="(u, index) in dogList.urlList" :key="index" :src="(u as string)">
    <span v-show="dogList.isLoading">加载中......</span><br>
    <button @click="getDog">
    再来一只狗
    </button>
    </template>

    <script lang="ts">
    import { defineComponent } from 'vue'
    export default defineComponent({
    name: 'App',
    })
    </script>

    <script setup lang="ts">
    import useDog from './hooks/useDog'
    import useSum from './hooks/useSum'

    const { sum, increment, decrement } = useSum()
    const { dogList, getDog } = useDog()
    </script>


四、 路由

4.1、对路由的理解

image-20231018144351536

4.2、基本切换效果

  • Vue3中要使用vue-router的最新版本,目前是4版本。

  • 路由配置文件代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    // 创建一个路由器,并暴露出去

    import About from '@/components/About.vue'
    // 引入一个一个可能要呈现组件
    import Home from '@/components/Home.vue'
    import News from '@/components/News.vue'
    // 第一步:引入createRouter
    import { createRouter, createWebHistory } from 'vue-router'

    // 第二步:创建路由器
    const router = createRouter({
    history: createWebHistory(), // 路由器的工作模式(稍后讲解)
    routes: [
    // 一个一个的路由规则
    {
    path: '/home',
    component: Home,
    },
    {
    path: '/news',
    component: News,
    },
    {
    path: '/about',
    component: About,
    },
    ],
    })

    // 暴露出去router
    export default router
  • main.ts代码如下:

    1
    2
    3
    4
    import router from './router/index'
    app.use(router)

    app.mount('#app')
  • App.vue代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <template>
    <div class="app">
    <h2 class="title">Vue路由测试</h2>
    <!-- 导航区 -->
    <div class="navigate">
    <RouterLink to="/home" active-class="active">首页</RouterLink>
    <RouterLink to="/news" active-class="active">新闻</RouterLink>
    <RouterLink to="/about" active-class="active">关于</RouterLink>
    </div>
    <!-- 展示区 -->
    <div class="main-content">
    <RouterView></RouterView>
    </div>
    </div>
    </template>

    <script lang="ts" setup name="App">
    import {RouterLink,RouterView} from 'vue-router'
    </script>

4.3、 两个注意点

  1. 路由组件通常存放在pagesviews文件夹,一般组件通常存放在components文件夹。

  2. 通过点击导航,视觉效果上“消失” 了的路由组件,默认是被卸载掉的,需要的时候再去挂载


4.4、路由器工作模式

  1. history模式

    优点:URL更加美观,不带有#,更接近传统的网站URL

    缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有404错误。

    1
    2
    3
    4
    const router = createRouter({
    history:createWebHistory(), //history模式
    /******/
    })
  2. hash模式

    优点:兼容性更好,因为不需要服务器端处理路径。

    缺点:URL带有#不太美观,且在SEO优化方面相对较差。

    1
    2
    3
    4
    const router = createRouter({
    history:createWebHashHistory(), //hash模式
    /******/
    })

4.5、to的两种写法

1
2
3
4
5
<!-- 第一种:to的字符串写法 -->
<router-link active-class="active" to="/home">主页</router-link>

<!-- 第二种:to的对象写法 -->
<router-link active-class="active" :to="{path:'/home'}">Home</router-link>

4.6、命名路由

作用:可以简化路由跳转及传参(后面就讲)。

给路由规则命名:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
routes:[
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News,
},
{
name:'guanyu',
path:'/about',
component:About
}
]

跳转路由:

1
2
3
4
5
<!--简化前:需要写完整的路径(to的字符串写法) -->
<router-link to="/news/detail">跳转</router-link>

<!--简化后:直接通过名字跳转(to的对象写法配合name属性) -->
<router-link :to="{name:'guanyu'}">跳转</router-link>

4.7、嵌套路由

  1. 编写News的子路由:Detail.vue

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <template>
    <div class="detail">
    {{ query.content }}
    </div>
    </template>

    <script setup lang="ts">
    import { toRefs } from 'vue'
    import { useRoute } from 'vue-router'

    const { query } = toRefs(useRoute())
    </script>

  2. 配置路由规则,使用children配置项:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    const router = createRouter({
    history: createWebHistory(),
    routes: [
    {
    name: 'zhuye',
    path: '/home',
    component: Home,
    },
    {
    name: 'xinwen',
    path: '/news',
    component: News,
    children: [
    {
    name: 'xiang',
    path: 'detail', // 子路由的路径不需要加斜杠/
    component: Detail,
    },
    ],
    },
    {
    name: 'guanyu',
    path: '/about',
    component: About,
    },
    ],
    })
    export default router

  3. 记得去News.vue组件中预留一个<router-view>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    // News.vue
    <template>
    <div class="news">
    <ul>
    <li v-for="(item, index) in list" :key="index">
    <RouterLink
    :to="{
    name: 'Detail',
    query: {
    id: item.id,
    content: item.content,
    },
    }"
    >
    {{ item.title }}
    </RouterLink>
    </li>
    </ul>
    <RouterView />
    </div>
    </template>

    <script setup lang="ts" name="News">
    import { reactive } from 'vue'

    const list = reactive([
    {
    id: 1,
    title: '新闻1',
    content: '新闻1的详情',
    },
    {
    id: 2,
    title: '新闻2',
    content: '新闻2的详情',
    },
    {
    id: 3,
    title: '新闻3',
    content: '新闻3的详情',
    },
    ])
    </script>

image-20240614000448855


4.8、路由传参

1)、query参数

传递参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// News.vue
<template>
<div class="news">
<ul>
<li v-for="(item, index) in list" :key="index">
<RouterLink
:to="{
name: 'Detail',
query: {
id: item.id,
content: item.content,
},
}"
>
{{ item.title }}
</RouterLink>
</li>
</ul>
<RouterView />
</div>
</template>

<script setup lang="ts" name="News">
import { reactive } from 'vue'

const list = reactive([
{
id: 1,
title: '新闻1',
content: '新闻1的详情',
},
{
id: 2,
title: '新闻2',
content: '新闻2的详情',
},
{
id: 3,
title: '新闻3',
content: '新闻3的详情',
},
])
</script>

接收参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Detail.vue
<template>
<div class="detail">
{{ query.content }}
</div>
</template>

<script setup lang="ts">
import { toRefs } from 'vue'
import { useRoute } from 'vue-router'

const { query } = toRefs(useRoute())
</script>


2)、params参数

需在路由中占位

传递参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- 跳转并携带params参数(to的对象写法) -->
<template>
<div class="news">
<ul>
<li v-for="(item, index) in list" :key="index">
<RouterLink
:to="{
name: 'Detail',
params: {
id: item.id,
content: item.content,
},
}"
>
{{ item.title }}
</RouterLink>
</li>
</ul>
<RouterView />
</div>
</template>

接收参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<div class="detail">
{{ params.id }}、{{ params.content }}
</div>
</template>

<script setup lang="ts">
import { toRefs } from 'vue'
import { useRoute } from 'vue-router'

const { params } = toRefs(useRoute())
</script>

在路由中占位:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
history: createWebHistory(), // 路由的工作模式
routes: [
{
path: '/news',
component: () => import('@/views/News.vue'),
children: [
{
path: 'detail/:id/:content?', // 占位要和跳转传参保持一致 ?:是可传可不传
name: 'Detail',
component: () => import('@/views/Detail.vue'),
},
],
},
],
})

export default router

备注1:传递params参数时,若使用to的对象写法,必须使用name配置项,不能用path

备注2:传递params参数时,需要提前在路由中占位。


4.9、路由的props配置

上述路由接收参数的时候、需要写大量的代码

1
2
3
import { toRefs } from 'vue';
import { useRoute } from 'vue-router';
let { params, query } = toRefs(useRoute());

props作用:让路由组件更方便的收到参数(可以将路由参数作为props传给组件),在组件中直接用defineProps便可接收到其他路由组件传递过来的参数

这种写法其实就是类似于自定义组件的传参

1
类似于<Detail a=“1” b="2" c="3"><Detail/>

1)、props的布尔值写法(只适用于params传参)

作用:将路由收到的所有params参数作为props传给当前组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!-- orderList.vue -->
<template>
<div class="orderList">
<ul>
<li @click="toDetail">
跳转到详情页
</li>
</ul>
</div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'

const router = useRouter()
const toDetail = () => {
router.push({
name: 'detail',
params: {
id: '323243',
content: '详情内容',
},
})
}
</script>

<!-- 路由index.ts -->
{
name:'detail',
path:'detail/:id/:content?',
component:Detail,
props:true
}

<!-- detail.vue -->
<template>
<div class="detail">
{{ id }}、{{ content }}
</div>
</template>

<script setup lang="ts">
defineProps(['id', 'content'])
</script>

2)、props的函数写法

作用:把返回的对象中每一组key-value作为props传给Detail组件(params、query可使用,更推荐query使用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!-- orderList.vue -->
<template>
<div class="orderList">
<ul>
<li @click="toDetail">
跳转到详情页
</li>
</ul>
</div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'

const router = useRouter()
const toDetail = () => {
router.push({
name: 'detail',
query: {
id: '323243',
content: '详情内容',
},
})
}
</script>

<!-- 路由index.ts -->
{
name:'detail',
path:'detail',
component:Detail,
props(route){ // route中能取到query和params
return route.query
}
}

<!-- detail.vue -->
<template>
<div class="detail">
{{ id }}、{{ content }}
</div>
</template>

<script setup lang="ts">
defineProps(['id', 'content'])
</script>

3)、props的对象写法

作用:把对象中的每一组key-value作为props传给Detail组件(不常用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!-- orderList.vue -->
<template>
<div class="orderList">
<ul>
<li @click="toDetail">
跳转到详情页
</li>
</ul>
</div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'

const router = useRouter()
const toDetail = () => {
router.push({
name: 'detail',
})
}
</script>

<!-- 路由index.ts -->
{
name:'xiang',
path:'detail/:id/:content?',
component:Detail,
props: { // 这种不能接收到动态参数,在业务中意义不大,不常用
id: 666,
content: '哈哈'
}
}

<!-- detail.vue -->
<template>
<div class="detail">{{ id }}、{{ content }}</div>
</template>

<script setup lang="ts">
defineProps(['id', 'content'])
</script>

**注意:**这里都是应用在路由组件中,而不是自定义组件中。所以当组件中有使用defineProps接收参数的时候,首先要确认这是路由组件还是自定义组件。


4.10、 replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式。

  2. 浏览器的历史记录有两种写入方式:分别为pushreplace

    • push是追加历史记录(默认值)。
    • replace是替换当前记录。
  3. 开启replace模式:

    1
    <RouterLink replace .......>News</RouterLink>

4.11、 编程式导航

路由组件的两个重要的属性:$route$router变成了两个hooks

1
2
3
4
5
6
7
8
9
import {useRoute,useRouter} from 'vue-router'

const route = useRoute()
const router = useRouter()

console.log(route.query)
console.log(route.parmas)
console.log(router.push)
console.log(router.replace)

4.12、 重定向

  1. 作用:将特定的路径,重新定向到已有路由。

  2. 具体编码:

    1
    2
    3
    4
    {
    path:'/',
    redirect:'/about'
    }

五、pinia

pinia_example

5.1、 搭建 pinia 环境

第一步:npm install pinia

第二步:操作src/main.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
import { createApp } from 'vue'
import App from './App.vue'

/* 引入createPinia,用于创建pinia */
import { createPinia } from 'pinia'

/* 创建pinia */
const pinia = createPinia()
const app = createApp(App)

/* 使用插件 */{}
app.use(pinia)
app.mount('#app')

此时开发者工具中已经有了pinia选项


5.2、 选项式 Stores

1
2
import {defineStore} from 'pinia'
export const useCountStore = defineStore('count',{}) // 第二个参数是个对象

1)、存储+读取数据

  1. Store是一个保存:状态业务逻辑 的实体,每个组件都可以读取写入它。

  2. 它有三个概念:stategetteraction,相当于组件中的: datacomputedmethods

  3. 具体编码:src/store/countStore.ts

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    // 引入defineStore用于创建store
    import {defineStore} from 'pinia'

    // 定义并暴露一个store
    export const useCountStore = defineStore('count',{
    // 动作
    actions:{},
    // 状态
    state(){
    return {
    sum:6,
    school: '尚硅谷'
    }
    },
    // 计算
    getters:{}
    })
  4. 具体编码:src/store/loveTalkStore.ts

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // 引入defineStore用于创建store
    import {defineStore} from 'pinia'

    // 定义并暴露一个store
    export const useLoveTalkStore = defineStore('talk',{
    // 动作
    actions:{},
    // 状态
    state(){
    return {
    loveTalkList:[
    {id:'yuysada01',content:'你今天有点怪,哪里怪?怪好看的!'},
    {id:'yuysada02',content:'草莓、蓝莓、蔓越莓,你想我了没?'},
    {id:'yuysada03',content:'心里给你留了一块地,我的死心塌地'}
    ]
    }
    },
    // 计算
    getters:{}
    })
  5. 组件中使用state中的数据

    Count.vue

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <template>
    <h2>当前求和为:{{ countStore.sum }}</h2>
    </template>

    <script setup lang="ts" name="Count">
    // 引入对应的useXxxxxStore
    import {useCountStore} from '@/store/countStore'
    ``
    // 调用useXxxxxStore得到对应的store
    const countStore = useCountStore()
    </script>

    LoveTalk.vue

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <template>
    <ul>
    <li v-for="talk in loveTalkStore.loveTalkList" :key="talk.id">
    {{ talk.content }}
    </li>
    </ul>
    </template>

    <script setup lang="ts" name="Count">
    import axios from 'axios'
    import { useLoveTalkStore } from '@/store/loveTalkStore'

    const loveTalkStore = useLoveTalkStore()
    </script>

2)、 修改数据 (三种方式)

  1. 第一种修改方式,直接修改

    1
    2
    // 在vue组件中修改
    countStore.sum = 666
  2. 第二种修改方式:批量修改

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // 在vue组件中修改
    // 1)对象形式
    countStore.$patch({
    sum:999,
    school:'atguigu'
    })

    // 2)函数形式
    countStore.$patch((state) => {
    state.sum=999,
    state.school='atguigu'
    })
  3. 第三种修改方式:借助action修改(action中可以编写一些业务逻辑)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // 在pinia中修改
    import { defineStore } from 'pinia'

    export const useCountStore = defineStore ('count', {
    actions: {
    //加
    increment(value:number) {
    if (this.sum < 10) {
    //操作countStore中的sum
    this.sum += value
    }
    }
    }
    })

    // 在组件中调用action
    let optVal = ref(1);
    const countStore = useCountStore()
    //在函数中调用
    countStore.increment(optVal.value)

3)、 storeToRefs

  • 借助storeToRefsstore中的数据(state,getters)转为ref响应对象,方便在模板中使用。
  • 注意:pinia提供的storeToRefs只会将数据做转换,而VuetoRefs会转换store中所有的数据(actions state等等)。
  • action 的 increment 可以直接解构,无需使用 storeToRefs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
<div class="count">
<h2>当前求和为:{{sum}}</h2>
</div>
</template>

<script setup lang="ts" name="Count">
import { useCountStore } from '@/store/count'
/* 引入storeToRefs */
import { storeToRefs } from 'pinia'

/* 得到countStore */
const countStore = useCountStore()
/* 使用storeToRefs转换countStore,随后解构(action 的 increment 可以直接解构无需使用storeToRefs) */
const {sum} = storeToRefs(countStore)
</script>

image-20240625001950272


4)、 getters

  1. 概念:当state中的数据,需要经过处理后再使用时,可以使用getters配置。

  2. 追加getters配置。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    // 引入defineStore用于创建store
    import {defineStore} from 'pinia'

    // 定义并暴露一个store
    export const useCountStore = defineStore('count',{
    // 动作
    actions:{
    /************/
    },
    // 状态
    state(){
    return {
    sum:1,
    school:'atguigu'
    }
    },
    // 计算
    getters: {
    // 箭头函数
    doubleSum: (state): number => state.sum * 2,
    // 普通函数
    upperSchool(): string {
    return (this.school = '希望小学');
    }
    }
    })
  3. 组件中读取数据:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <template>
    <div class="count">
    <h2>当前求和为:{{ sum }}, 当前sun的两倍{{ doubleSum }}。 小明的多大了? {{ age }}岁</h2>
    <h2>当前学校为:{{ upperSchool }}</h2>
    </div>
    </template>

    <script setup lang="ts">
    import { useCountStore } from '@/store/countStore'
    import { storeToRefs } from 'pinia'

    const countStore = useCountStore()
    const { sum, age, doubleSum, upperSchool } = storeToRefs(countStore)
    </script>


5)、 $subscribe

通过 store 的 $subscribe() 方法侦听 state 及其变化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// loveTalkStore.ts
import axios from 'axios'
import { nanoid } from 'nanoid'
import { defineStore } from 'pinia'

export const useLoveTalkStore = defineStore('loveTalk', {
state() {
return {
loveTalkList: JSON.parse(localStorage.getItem('loveTalkList') as string) || [],
}
},
actions: {
async getLoveTalk() {
const {
data: { content: title },
} = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json')
this.loveTalkList.unshift({ id: nanoid(), title })
},
},
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 在组件中使用 LoveTalk.vue
<template>
<div class="LoveTalk">
<button @click="queryLoveTalk">
获取一句土味情话
</button>
<ul>
<li v-for="(item, index) in loveTalkList" :key="index">
{{ item.title }}
</li>
</ul>
</div>
</template>

<script setup lang="ts">
import { useLoveTalkStore } from '@/store/loveTalkStore'
import { storeToRefs } from 'pinia'

const loveTalkStore = useLoveTalkStore()
const { getLoveTalk } = loveTalkStore
const { loveTalkList } = storeToRefs(loveTalkStore)

function queryLoveTalk() {
getLoveTalk()
}
// 组件中使用$subscribe
loveTalkStore.$subscribe((mutate, state) => {
console.log('talkStore里面保存的数据发生了变化', mutate, state)
localStorage.setItem('loveTalkList', JSON.stringify(state.loveTalkList))
})
</script>


5.3、 store组合式写法

和选项式写法唯一不同的是pinia中的defineStor()中的写法不一样,其他都一样(在组件中修改数据,使用一些api)

1
2
3
4
5
import { defineStore } from 'pinia'

export const useCountStore = defineStore('count', () => { // 第二个参数是个函数
return {} // 需要把定义的数据/方法return出去
})

loveTalkStore.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import axios from 'axios'
import { nanoid } from 'nanoid'
import { defineStore } from 'pinia'
import { reactive } from 'vue'

export const useLoveTalkStore = defineStore('loveTalk', () => {
// talkList就是state
const loveTalkList = reactive(JSON.parse(localStorage.getItem('loveTalkList') as string) || [])

// getATalk函数相当于action
const getLoveTalk = async () => {
// 发请求,下面这行的写法是:连续解构赋值+重命名
const {
data: { content: title },
} = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json')
// 把请求回来的字符串,包装成一个对象
const obj = { id: nanoid(), title }
// 放到数组中
loveTalkList.unshift(obj)
}
return { loveTalkList, getLoveTalk }
})

countStore.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

interface StoreData {
sum: number
school: string
}
export const useCountStore = defineStore('count', () => {
const sum = ref(1)
const school = ref('school')

const doubleSum = computed(() => sum.value * 2)
const upperSchool = computed(() => school)

const increment = (val: StoreData) => {
sum.value += val.sum
school.value = val.school
}

return { sum, school, doubleSum, upperSchool, increment }
})

六、组件通信

Vue3组件通信和Vue2的区别:

  • 移出事件总线,使用mitt代替。
  • vuex换成了pinia
  • .sync优化到了v-model里面了。
  • $listeners所有的东西,合并到$attrs中了。
  • $children被砍掉了。

常见搭配形式:

image-20231119185900990

6.1、 props

概述:props是使用频率最高的一种通信方式,常用与 :父 ↔ 子

  • 父传子:属性值是非函数
  • 子传父:属性值是函数

父组件:Father.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<div class="father">
<h3>父组件</h3>
<p>汽车:{{ car }}</p>
<p>儿子给的玩具:{{ toy }}</p>
<Child :car="car" :send-toy="getToy" />
</div>
</template>

<script setup lang="ts" name="Father">
import { ref } from 'vue'
import Child from './Child.vue'

const car = ref('奔驰')
const toy = ref('')

function getToy(val: string) {
toy.value = val
}
</script>

子组件:Child.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div class="child">
<h3>子组件</h3>
<p>玩具:{{ toy }}</p>
<p>父亲给的车:{{ car }}</p>
<button @click="giveToy">
把玩具给父亲
</button>
</div>
</template>

<script setup lang="ts" name="Child">
import { ref } from 'vue'

const props = defineProps(['car', 'sendToy']) // 接收参数
const toy = ref('奥特曼')

function giveToy() {
props.sendToy(toy.value) // 通过函数的形参将子级的数据传递给父级函数的实参并调用
}
</script>


6.2、 自定义事件defineEmits

  1. 概述:自定义事件常用于:子 => 父。
  2. 注意区分好:原生事件、自定义事件。
  • 原生事件:
    • 事件名是特定的(clickmosueenter等等)
    • 事件对象$event: 是包含事件相关信息的对象(pageXpageYtargetkeyCode
  • 自定义事件:
    • 事件名是任意名称
    • 事件对象$event: 是调用emit时所提供的数据,可以是任意类型!!!

父组件:Father.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<div class="father">
<h3>父组件</h3>
<h4>子给的玩具:{{ toy }}</h4>
<!-- 给子组件Child绑定事件 -->
<Child @send-toy="saveToy" />
</div>
</template>

<script setup lang="ts" name="Father">
import { ref } from 'vue'
import Child from './Child.vue'
// 数据
const toy = ref('______')
// 用于保存传递过来的玩具
function saveToy(value: string) {
toy.value = value
}
</script>

子组件:Child.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<div class="child">
<h3>子组件</h3>
<h4>玩具:{{ toy }}</h4>
<button @click="giveToy">
把玩具给父亲
</button>
</div>
</template>

<script setup lang="ts" name="Child">
import { ref } from 'vue'
// 声明事件
const emits = defineEmits(['send-toy'])
// 数据
const toy = ref('奥特曼')
function giveToy() {
emits('send-toy', toy.value)
}
</script>

扩展:当有多个参数的时候,获取事件对象就需要使用$event去占位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
><template>
<div class="child">
<button @click="test(5, 6, $event)">
测试
</button>
</div>
></template>

><script setup lang="ts" name="Child">
>function test(a, b, e) {
console.log(e)
>}
></script>


6.3、 mitt

概述:与消息订阅与发布(pubsub)功能类似,可以实现任意组件间通信。

【第一步】:安装mitt

1
pnpm add mitt

【第二步】:新建文件:src\utils\emitter.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 引入mitt 
import mitt from "mitt";

// 创建emitter
const emitter = mitt()

// 创建并暴露mitt
export default emitter


/* 其他页面使用的语法
// 绑定事件(接收)
emitter.on('abc',(value)=>{
console.log('abc事件被触发',value)
})
emitter.on('xyz',(value)=>{
console.log('xyz事件被触发',value)
})

setInterval(() => {
// 触发事件(传递)
emitter.emit('abc',666)
emitter.emit('xyz',777)
}, 1000);

setTimeout(() => {
// 解绑事某个件
emitter.off('abc')
// 清理全部事件
emitter.all.clear()
}, 3000);
*/

【第三步】:接收数据的组件中:绑定事件、同时在销毁前解绑事件:

1
2
3
4
5
6
7
8
9
10
11
12
import emitter from "@/utils/emitter";
import { onUnmounted } from "vue";

// 绑定事件
emitter.on('send-toy',(value)=>{
console.log('send-toy事件被触发',value)
})

onUnmounted(()=>{
// 解绑事件
emitter.off('send-toy')
})

【第四步】:提供数据的组件,在合适的时候触发事件

1
2
3
4
5
6
import emitter from "@/utils/emitter";

function sendToy(){
// 触发事件
emitter.emit('send-toy',toy.value)
}

注意这个重要的内置关系,总线依赖着这个内置关系


6.4、 v-model

概述:实现 父↔子 之间相互通信。

1)、v-model用在html标签上(前序知识)

1
2
3
4
5
6
7
8
9
<!-- html标签上使用v-model指令 -->
<input type="text" v-model="userName">

<!-- html标签上使用v-model本质 -->
<input
type="text"
:value="userName"
@input="userName = ($event.target as HTMLInputElement).value"
>

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<input
type="text"
:value="userName"
@input="userName = ($event.target as HTMLInputElement).value"
>
</template>

<script setup lang="ts" name="Father">
import { ref } from 'vue'
</script>

---------- 等同于如下代码 ----------

<template>
<input type="text" :value="userName" @input="change" />
</template>

<script setup lang="ts" name="Father">
let userName = ref('')
function change(e: Event) {
const inputElement = e.target as HTMLInputElement
userName.value = inputElement.value
}
</script>

2)、v-model用在组件标签上(前序知识)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- 组件标签上使用v-model指令 -->
<AtguiguInput v-model="userName"/>

<!-- 组件标签上v-model的本质 -->
<AtguiguInput :modelValue="userName" @update:model-value="userName = $event"/>

**注意:**
<!-- 在组件标签上v-model本质中,vue2和vue3稍微有所不同 -->

传参名:
- vue2
:value
- vue3
:modelValue


自定义事件名:
- vue2
@input
- vue3
@update:model-value

使用:

Father.vue

1
<AtguiguInput v-model="userName"/>

AtguiguInput.vue组件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<template>
<div class="box">
<!-- 将接收的value值赋给input元素的value属性,目的是:为了呈现数据 -->
<!-- 给input元素绑定原生input事件,触发input事件时,进而触发update:model-value事件 -->
<input
type="text"
:value="modelValue"
@input="emit('update:model-value', $event.target.value)"
>
</div>
</template>

<script setup lang="ts" name="AtguiguInput">
// 接收props
defineProps(['modelValue'])
// 声明事件
const emit = defineEmits(['update:model-value'])
</script>

// Vue 3.4+ 写法
// 父组件
<AtguiguInput v-model="userName"/>

// 子组件
<template>
<input v-model="model" />
</template>

<script setup>
// 1. 就这一行,没了!
const model = defineModel()
</script>

案例:

1
2
3
4
5
6
7
8
9
// 父组件
<template>
<VanPopupComponent v-model:sign-show="signShow" />
</template>

<script setup lang="ts">
const signShow = ref(true)
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 子组件
<template>
<van-popup
v-model:show="localSignShow"
position="bottom"
round closeable
@update:show="onUpdateSignShow"
>
<p class="popup-title">签约提示</p>
<div class="popup-content">54545</div>
</van-popup>
</template>

<script setup lang="ts">
interface VanPopupProps {
signShow: boolean
}

const props = withDefaults(defineProps<VanPopupProps>(), {
signShow: false,
})
const emit = defineEmits(['update:signShow'])

const localSignShow = ref(props.signShow)

watch(() => props.signShow, val => localSignShow.value = val)

const onUpdateSignShow = (val: boolean) => {
localSignShow.value = val
emit('update:signShow', val)
}
</script>

Vue 3.4+ 简写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 父组件
<template>
<VanPopupComponent v-model:sign-show="signShow" />
</template>

<script setup lang="ts">
const signShow = ref(true)
</script>


// 子组件
<template>
<van-popup
v-model:show="signShow"
position="bottom"
round closeable
>
<p class="popup-title">签约提示</p>
<div class="popup-content">54545</div>
</van-popup>
</template>

<script setup lang="ts">
// 因为父组件将v-model默认名modelValue改成了sign-show,因此defineModel('signShow')中需要传递个修改之后的名字
const signShow = defineModel<boolean>('signShow')
</script>

2-1、修改传递参数的默认值

更换modelValue,例如改成abc

1
2
3
4
5
<!-- 也可以更换value,例如改成abc-->
<AtguiguInput v-model:abc="userName"/>

<!-- 上面代码的本质如下 -->
<AtguiguInput :abc="userName" @update:abc="userName = $event"/>

AtguiguInput组件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<div class="box">
<input
type="text"
:value="abc"
@input="emit('update:abc', $event.target.value)"
>
</div>
</template>

<script setup lang="ts" name="AtguiguInput">
// 接收props
defineProps(['abc'])
// 声明事件
const emit = defineEmits(['update:abc'])
</script>

2-2、组件标签上多次使用v-model

如果value可以更换,那么就可以在组件标签上多次使用v-model

1
<AtguiguInput v-model:abc="userName" v-model:xyz="password"/>

AtguiguInput组件中:

1
2
3
4
5
6
7
8
9
10
11
12
<template>
<!-- 组件标签上多次使用`v-model` -->
<input :value="ming" type="text" @input="emits('update:ming', ($event.target as HTMLInputElement).value)">
<br>
<br>
<input :value="mima" type="text" @input="emits('update:mima', ($event.target as HTMLInputElement).value)">
</template>

<script setup lang="ts" name="AtguiguInput">
defineProps(['ming', 'mima'])
const emits = defineEmits(['update:ming', 'update:mima'])
</script>
2-3、v-model二次封装组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 子组件

<template>
<el-dialog v-model="getShow" title="Shipping address" width="80%">
你好
</el-dialog>
</template>

<script setup lang="ts">
const props = defineProps({
modelValue: {
type: Boolean,
default: false,
},
});
const emits = defineEmits(["update:model-value"]);

const getShow = computed({
get: () => props.modelValue,
set: (val) => {
emits("update:model-value", val);
},
});
</script>

<style scoped lang="scss"></style>

1
2
3
4
5
6
7
8
9
父组件
<template>
<StatisticsDialog v-model="dialogTableVisible" />
</template>

<script setup lang="ts">
const dialogTableVisible = ref(false)
</script>


6.5、 $attrs

  1. 概述:$attrs用于实现当前组件的父组件,向当前组件的子组件通信(祖→孙)。

  2. 具体说明:$attrs是一个对象,包含所有父组件传入的标签属性。

    注意:$attrs会自动排除props中声明的属性(可以认为声明过的 props 被子组件自己“消费”了),即$attrs中可以取到组件传递过来的参数,如果传值过来的参数在props中声明了,则不会在 $attrs中展示

image-20240807231752669

知识扩展

1
2
3
<Child v-bind="{x:100,y:200}"/>
等价于
<Child :x:100 :y:200}"/>

父组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<div class="father">
<h3>父组件</h3>
<Child :a="a" :b="b" :c="c" :d="d" v-bind="{ x: 100, y: 200 }" :update-a="updateA" />
</div>
</template>

<script setup lang="ts" name="Father">
import { ref } from 'vue'
import Child from './Child.vue'

const a = ref(1)
const b = ref(2)
const c = ref(3)
const d = ref(4)

function updateA(value) {
a.value += value
}
</script>

子组件:

1
2
3
4
5
6
7
8
9
10
11
<template>
<div class="child">
<h3>子组件</h3>
<GrandChild v-bind="$attrs" />
</div>
</template>

<script setup lang="ts" name="Child">
import GrandChild from './GrandChild.vue'
</script>

孙组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div class="grand-child">
<h3>孙组件</h3>
<h4>a:{{ a }}</h4>
<h4>b:{{ b }}</h4>
<h4>c:{{ c }}</h4>
<h4>d:{{ d }}</h4>
<h4>x:{{ x }}</h4>
<h4>y:{{ y }}</h4>
<button @click="updateA(666)">
点我更新A
</button>
</div>
</template>

<script setup lang="ts" name="GrandChild">
defineProps(['a', 'b', 'c', 'd', 'x', 'y', 'updateA'])
</script>


6.6、 $refs $parent

  1. 概述:

    • $refs用于 :父→子。
    • $parent用于:子→父。
  2. 原理如下:

    属性说明
    $refs值为对象,包含所有被ref属性标识的DOM元素或组件实例。
    $parent值为对象,当前组件的父组件实例对象。

父组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<template>
<div class="father">
<h3>父组件</h3>
<h4>房产:{{ house }}</h4>
<button @click="changeToy">
修改Child1的玩具
</button>
<button @click="changeComputer">
修改Child2的电脑
</button>
<button @click="getAllChild($refs)">
让所有孩子的书变多
</button>
<Child1 ref="c1" />
<Child2 ref="c2" />
</div>
</template>

<script setup lang="ts" name="Father">
import { ref } from 'vue'
import Child1 from './Child1.vue'
import Child2 from './Child2.vue'

const c1 = ref()
const c2 = ref()

// 数据
const house = ref(4)
// 方法
function changeToy() {
c1.value.toy = '小猪佩奇'
}
function changeComputer() {
c2.value.computer = '华为'
}
function getAllChild(refs: { [key: string]: any }) {
for (const key in refs) {
refs[key].book += 3
}
}
// 向外部提供数据
defineExpose({ house })
</script>

<style scoped>
.father {
padding: 20px;
background-color: rgb(165 164 164);
border-radius: 10px;
}

.father button {
margin-bottom: 10px;
margin-left: 10px;
}
</style>

子组件:Child1.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<template>
<div class="child1">
<h3>子组件1</h3>
<h4>玩具:{{ toy }}</h4>
<h4>书籍:{{ book }} 本</h4>
<button @click="minusHouse($parent)">
干掉父亲的一套房产
</button>
</div>
</template>

<script setup lang="ts" name="Child1">
import { ref } from 'vue'
// 数据
const toy = ref('奥特曼')
const book = ref(3)

// 方法
function minusHouse(parent: any) {
console.log(parent)
parent.house -= 1
}

// 把数据交给外部
defineExpose({ toy, book })
</script>

<style scoped>
.child1 {
padding: 20px;
margin-top: 20px;
background-color: skyblue;
border-radius: 10px;
box-shadow: 0 0 10px black;
}
</style>

子组件:Child2.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div class="child2">
<h3>子组件2</h3>
<h4>电脑:{{ computer }}</h4>
<h4>书籍:{{ book }} 本</h4>
</div>
</template>

<script setup lang="ts" name="Child2">
import { ref } from 'vue'
// 数据
const computer = ref('联想')
const book = ref(6)
// 把数据交给外部
defineExpose({ computer, book })
</script>

<style scoped>
.child2 {
padding: 20px;
margin-top: 20px;
background-color: orange;
border-radius: 10px;
box-shadow: 0 0 10px black;
}
</style>

image-20240811220050879


6.7、 provide、inject

  1. 概述:实现祖孙组件直接通信

  2. 具体使用:

    • 在祖先组件中通过provide配置向后代组件提供数据
    • 在后代组件中通过inject配置来声明接收数据
  3. 具体编码:

    【第一步】父组件中,使用provide提供数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    <template>
    <div class="father">
    <h3>父组件</h3>
    <h4>银子:{{ money }}万元</h4>
    <h4>车子:一辆{{ car.brand }}车,价值{{ car.price }}万元</h4>
    <Child />
    </div>
    </template>

    <script setup lang="ts" name="Father">
    import { provide, reactive, ref } from 'vue'
    import Child from './Child.vue'

    const money = ref(100)
    const car = reactive({
    brand: '奔驰',
    price: 100,
    })
    function updateMoney(value: number) {
    money.value -= value
    }

    // 向后代提供数据
    // 语法:provide(命名, 传参);
    provide('moneyContext', { money, updateMoney }) // 注意money不能用money.value,用.vue就是传递的一个数字 而不是一个响应式数据
    provide('car', car)
    </script>

    <style scoped>
    .father {
    padding: 20px;
    background-color: rgb(165 164 164);
    border-radius: 10px;
    }
    </style>

    注意:子组件中不用编写任何东西,是不受到任何打扰的

    【第二步】孙组件中使用inject配置项接受数据。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <template>
    <div class="grand-child">
    <h3>我是孙组件</h3>
    <h4>银子:{{ money }}</h4>
    <h4>车子:一辆{{ car.brand }}车,价值{{ car.price }}万元</h4>
    <button @click="updateMoney(6)">
    花爷爷的钱
    </button>
    </div>
    </template>

    <script setup lang="ts" name="GrandChild">
    import { inject } from 'vue'

    // inject(命名, 默认参数);
    const { money, updateMoney } = inject('moneyContext', { money: 0, updateMoney: (param: number) => {} })
    const car = inject('car', { brand: '未知', price: 0 })
    </script>

    <style scoped>
    .grand-child {
    padding: 20px;
    background-color: orange;
    border-radius: 10px;
    box-shadow: 0 0 10px black;
    }
    </style>


6.8、 pinia

参考之前pinia部分的讲解


6.9、 slot

1)、 默认插槽

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
父组件中:
<Category title="今日热门游戏">
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
</Category>
子组件中:
<template>
<div class="item">
<h3>{{ title }}</h3>
<!-- 默认插槽 -->
<slot></slot>
</div>
</template>

2)、 具名插槽

父组件:v-slot: xxx
子组件:name= “xxx”

其中v-slot: xxx 可以简写成 #xxx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
父组件中:
<Category title="今日热门游戏">
<template v-slot:s1>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
</template>
<template #s2>
<a href="">更多</a>
</template>
</Category>

子组件中:
<template>
<div class="item">
<h3>{{ title }}</h3>
<slot name="s1"></slot>
<slot name="s2"></slot>
</div>
</template>

3)、 作用域插槽

  1. 理解:插槽的内容无法访问到子组件的状态,然而在某些场景下插槽的内容可能想要同时使用父组件域内和子组件域内的数据。要做到这一点,我们需要一种方法来让子组件在渲染时将一部分数据提供给插槽。

  2. 具体编码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    父组件中:
    <Game v-slot="slotProps"> // 这几种写法都一样
    <!-- <Game v-slot:default="slotProps"> -->
    <!-- <Game #default="slotProps"> -->
    <!-- <Game #="params"> -->
    <ul>
    <li v-for="g in slotProps.games" :key="g.id">{{ g.name }}</li>
    </ul>
    </Game>

    子组件中:
    <template>
    <div class="category">
    <h2>今日游戏榜单</h2>
    <slot :games="games" a="哈哈" />
    </div>
    </template>


    <script setup lang="ts" name="Category">
    import {reactive} from 'vue'
    let games = reactive([
    {id:'asgdytsa01',name:'英雄联盟'},
    {id:'asgdytsa02',name:'王者荣耀'},
    {id:'asgdytsa03',name:'红色警戒'},
    {id:'asgdytsa04',name:'斗罗大陆'}
    ])
    </script>

七、 directive自定义指令

TIP

只有当所需功能只能通过直接的 DOM 操作来实现时,才应该使用自定义指令。其他情况下应该尽可能地使用 v-bind 这样的内置指令来声明式地使用模板,这样更高效,也对服务端渲染更友好。

自定义指令会有指令钩子,当需要在指令中用到多个钩子则需要使用对象的形式来完成。

1
2
3
4
5
6
7
8
9
10
11
// 局部
const vFocus = {
created(el, binding, vnode) {},
... ...
};

// 全局
app.directive('focus', {
created(el, binding, vnode) {},
... ...
})

如果只需要需要在 mountedupdated 钩子上上实现相同的行为,除此之外并不需要其他钩子。这种情况下我们可以直接用一个函数来定义指令

1
2
3
4
5
6
7
// 局部
const vFocus = el => el.focus();

// 全局
app.directive('focus', (el, binding, vnode) => {
/* ... */
})

7.1、 局部自定义指令

1)、在使用语法糖

在使用<script setup>的情况下

1
2
3
4
5
6
7
8
9
10
11
12
<template>
<input v-focus>
</template>

<script setup>
const vFocus = {
mounted: el => el.focus(),
}
// 简写形式
// const vFocus = el => el.focus();
</script>

1)、在未使用语法糖

在没有使用 <script setup> 的情况下,自定义指令需要通过 directives 选项注册:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
<input v-focus>
</template>

<script>
export default {
directives: {
focus: {
mounted: el => el.focus(),
},
// 简写形式1
// focus(el) {
// el.focus();
// }

// 简写形式2
// focus: el => el.focus()
},
setup() {
/* ... */
},
}
</script>


7.2、 全局自定义指令

将一个自定义指令全局注册到应用层级也是一种常见的做法:

1
2
3
4
5
6
7
8
9
10
11
12
const app = createApp({})

// 使 v-focus 在所有组件中都可用
app.directive('focus', {
created(el, binding, vnode) {},
... ...
})

// 简写
app.directive('focus', (el, binding, vnode) => {
/* ... */
})

7.3、 指令钩子

一个指令的定义对象可以提供几种钩子函数 (都是可选的):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

const myDirective = {
// 在绑定元素的 attribute 前
// 或事件监听器应用前调用
created(el, binding, vnode) {
// 下面会介绍各个参数的细节
},
// 在元素被插入到 DOM 前调用
beforeMount(el, binding, vnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都挂载完成后调用
mounted(el, binding, vnode) {},
// 绑定元素的父组件更新前调用
beforeUpdate(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都更新后调用
updated(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载前调用
beforeUnmount(el, binding, vnode) {},
// 绑定元素的父组件卸载后调用
unmounted(el, binding, vnode) {}
}

钩子参数

指令的钩子会传递以下几种参数:

  • el:指令绑定到的元素。这可以用于直接操作 DOM。
  • binding:一个对象,包含以下属性。
    • value:传递给指令的值。例如在 v-my-directive="1 + 1" 中,值是 2
    • oldValue:之前的值,仅在 beforeUpdateupdated 中可用。无论值是否更改,它都可用。
    • arg:传递给指令的参数 (如果有的话)。例如在 v-my-directive:foo 中,参数是 "foo"
    • modifiers:一个包含修饰符的对象 (如果有的话)。例如在 v-my-directive.foo.bar 中,修饰符对象是 { foo: true, bar: true }
    • instance:使用该指令的组件实例。
    • dir:指令的定义对象。
  • vnode:代表绑定元素的底层 VNode。
  • prevVnode:代表之前的渲染中指令所绑定元素的 VNode。仅在 beforeUpdateupdated 钩子中可用。

举例来说,像下面这样使用指令:

1
<div v-example:foo.bar="baz">

binding 参数会是一个这样的对象:

1
2
3
4
5
6
{
arg: 'foo',
modifiers: { bar: true },
value: /* `baz` 的值 */,
oldValue: /* 上一次更新时 `baz` 的值 */
}

和内置指令类似,自定义指令的参数也可以是动态的。举例来说:

1
2
<div v-example:[arg]="value"></div>
// 这里指令的参数会基于组件的 arg 数据属性响应式地更新。

7.4、 简化形式

对于自定义指令来说,一个很常见的情况是仅仅需要在 mountedupdated 上实现相同的行为,除此之外并不需要其他钩子。这种情况下我们可以直接用一个函数来定义指令,如下所示:

1
<div v-color="color"></div>
1
2
3
4
app.directive('color', (el, binding) => {
// 这会在 `mounted` 和 `updated` 时都调用
el.style.color = binding.value
})

八、 其它 API

8.1、 shallowRef 与 shallowReactiv

1)、 shallowRef

  1. 作用:创建一个浅层响应式数据,但只对顶层属性进行响应式处理。

  2. 用法:

    1
    let myVar = shallowRef(initialValue);
  3. 特点:只跟踪引用值的变化,不关心值内部的属性变化。简单来说只对 XXX.value = ‘111’的生效 对 obj.value.xxx = ‘111’不生效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<template>
<div class="app">
<h2>求和为:{{ sum }}</h2>
<h2>名字为:{{ person.name }}</h2>
<h2>年龄为:{{ person.age }}</h2>
<button @click="changeSum">
sum+1
</button>
<button @click="changeName">
修改名字
</button>
<button @click="changeAge">
修改年龄
</button>
<button @click="changePerson">
修改整个人
</button>
</div>
</template>

<script setup lang="ts" name="App">
import { shallowRef } from 'vue'

const sum = shallowRef(0)
const person = shallowRef({
name: '张三',
age: 18,
})
function changeSum() { // 改变视图
sum.value += 1
}
function changeName() { // 未改变视图
person.value.name = '李四'
}
function changeAge() { // 未改变视图
person.value.age += 1
}
function changePerson() { // 改变视图
person.value = { name: 'tony', age: 100 }
}
</script>

2)、 shallowReactive

  1. 作用:创建一个浅层响应式对象,只会使对象的最顶层属性变成响应式的,对象内部的嵌套属性则不会变成响应式的

  2. 用法:

    1
    const myObj = shallowReactive({ ... });
  3. 特点:对象的顶层属性是响应式的,但嵌套对象的属性不是。简单来说只对第一层的属性值生效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<template>
<div class="app">
<h2>求和为:{{ sum }}</h2>
<h2>名字为:{{ person.name }}</h2>
<h2>年龄为:{{ person.age }}</h2>
<h2>汽车为:{{ car }}</h2>
<button @click="changeBrand">
修改品牌
</button>
<button @click="changeColor">
修改颜色
</button>
<button @click="changeEngine">
修改发动机
</button>
</div>
</template>

<script setup lang="ts" name="App">
import { shallowReactive } from 'vue'

const car = shallowReactive({
barnd: '奔驰',
options: {
color: '红色',
engine: 'V8',
},
})
function changeBrand() { // 改变视图
car.barnd = '宝马'
}
function changeColor() { // 改变视图
car.options.color = '紫色'
}
function changeEngine() { // 改变视图
car.options.engine = 'V12'
}
</script>

3)、 总结

通过使用 shallowRef()shallowReactive() 来绕开深度响应。浅层式 API 创建的状态只在其顶层是响应式的,对所有深层的对象不会做任何处理,避免了对每一个内部属性做响应式所带来的性能成本,这使得属性的访问变得更快,可提升性能。


8.2、 readonly 与 shallowReadonly

1)、 readonly

  1. 作用:用于创建一个对象的深只读副本。

  2. 用法:

    1
    2
    const original = reactive({ ... });
    const readOnlyCopy = readonly(original); // readonly的参数必须是一个响应式数据
  3. 特点:

    • 对象的所有嵌套属性都将变为只读。
    • 任何尝试修改这个对象的操作都会被阻止(在开发模式下,还会在控制台中发出警告)。
  4. 应用场景:

    • 创建不可变的状态快照。
    • 保护全局状态或配置不被修改。

2)、 shallowReadonly

  1. 作用:与 readonly 类似,但只作用于对象的顶层属性。

  2. 用法:

    1
    2
    const original = reactive({ ... });
    const shallowReadOnlyCopy = shallowReadonly(original);
  3. 特点:

    • 只将对象的顶层属性设置为只读,对象内部的嵌套属性仍然是可变的。

    • 适用于只需保护对象顶层属性的场景。


8.3、toRaw 与 markRaw

1)、 toRaw

  1. 作用:用于获取一个响应式对象的原始对象, toRaw 返回的对象不再是响应式的,不会触发视图更新。

    官网描述:这是一个可以用于临时读取而不引起代理访问/跟踪开销,或是写入而不触发更改的特殊方法。不建议保存对原始对象的持久引用,请谨慎使用。

    何时使用? —— 在需要将响应式对象传递给非 Vue 的库或外部系统时,使用 toRaw 可以确保它们收到的是普通对象

  2. 具体编码:

    1
    2
    3
    4
    5
    6
    7
    import { reactive,toRaw,markRaw,isReactive } from "vue";

    /* toRaw */
    // 响应式对象
    let person = reactive({name:'tony',age:18})
    // 原始对象
    let rawPerson = toRaw(person)

2)、 markRaw

  1. 作用:标记一个对象,使其永远不会变成响应式的。

    例如使用mockjs时,为了防止误把mockjs变为响应式对象,可以使用 markRaw 去标记mockjs

  2. 编码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    /* markRaw */
    let citys = markRaw([
    {id:'asdda01',name:'北京'},
    {id:'asdda02',name:'上海'},
    {id:'asdda03',name:'天津'},
    {id:'asdda04',name:'重庆'}
    ])
    // 根据原始对象citys去创建响应式对象citys2 —— 创建失败,因为citys被markRaw标记了
    let citys2 = reactive(citys)

8.4、customRef(自定义ref)

作用:创建一个自定义的ref,并对其依赖项跟踪和更新触发进行逻辑控制。

实现防抖效果hooks(useSumRef.ts):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { customRef } from 'vue'

export default function (initValue: string, delay: number) {
// track() 跟踪 trigger() 触发
const msg = customRef((track, trigger) => {
let timer: number
return {
get() {
track() // 告诉Vue数据msg很重要,要对msg持续关注,一旦变化就更新
return initValue
},
set(value) {
clearTimeout(timer)
timer = setTimeout(() => {
initValue = value
trigger() // 通知Vue数据msg变化了
}, delay)
},
}
})
return { msg }
}

组件中使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<div class="app">
<h2>{{ msg }}</h2>
<input v-model="msg" type="text">
</div>
</template>

<script setup lang="ts" name="App">
import useMsgRef from './useMsgRef'

// 使用Vue提供的默认ref定义响应式数据,数据一变,页面就更新
// let msg = ref('你好')

// 使用useMsgRef来定义一个响应式数据且有延迟效果
const { msg } = useMsgRef('你好', 2000)
</script>


九、Vue3新组件

9.1、 Teleport

  • 什么是Teleport?—— Teleport 是一种能够将我们的组件html结构移动到指定位置的技术。

app.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<div class="">
你好
</div>
<teleport to="body">
// to:插到指定的html位置
<Modal />
</teleport>
</template>

<script setup lang="ts">
import Modal from './components/Modal.vue'
</script>

Modal.vue

1
2
3
4
5
6
7
8
<template>
<div class="modal">
<h2>我是一个弹窗</h2>
<p>我是弹窗中的一些内容</p>
<button>关闭弹窗</button>
</div>
</template>


9.2、 Suspense(实验性功能)

  • 等待异步组件时渲染一些额外内容,让应用有更好的用户体验
  • 使用步骤:
    • 异步引入组件
    • 使用Suspense包裹组件,并配置好defaultfallback
1
2
3
import { defineAsyncComponent,Suspense } from "vue";
// defineAsyncComponent可使组件变成异步组件
const Child = defineAsyncComponent(()=>import('./Child.vue'))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<div class="app">
<h3>我是App组件</h3>
<Suspense>
<template #default>
<Child />
</template>
<template #fallback>
<h3>加载中.......</h3>
</template>
</Suspense>
</div>
</template>


9.3、 全局API转移到应用对象

  • app.component:注册全局组件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!-- hello.vue -->
    <template>
    <p>helloWord</p>
    </template>

    <!-- main.ts -->
    import Child from './components/Child.vue';
    app.component('Child', Child);

    <!-- app.vue -->
    <template>
    <Child />
    </template>
  • app.config.globalProperties:用于注册能够被应用内所有组件实例访问到的全局属性的对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!-- main.ts -->
    app.config.globalProperties.msg = 'hello'

    declare module 'vue' { // 解决msg在其他页面使用时ts报错,可单独写一个文件中,不推荐过度使用
    interface ComponentCustomProperties {
    msg: number
    }
    }

    <!-- app.vue -->
    <template>
    <p>{{ msg }}</p>
    </template>
  • app.mount

  • app.unmount

  • app.use


9.4、其他

  • 过渡类名 v-enter 修改为 v-enter-from、过渡类名 v-leave 修改为 v-leave-from

  • keyCode 作为 v-on 修饰符的支持。

  • v-model 指令在组件上的使用已经被重新设计,替换掉了 v-bind.sync。

  • v-ifv-for 在同一个元素身上使用时的优先级发生了变化。

  • 移除了$on$off$once 实例方法。

  • 移除了过滤器 filter

  • 移除了$children 实例 propert

    ……``