Vue

Vue

Vue3

官方文档简介 | Vue.js

1-创建vue工程

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

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

1683167182037-71c78210-8217-4e7d-9a83-e463035efbbe

1683167204081-582dc237-72bc-499e-9589-2cdfd452e62f

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?
## 是否添加JSX支持
√ Add JSX Support?
## 是否添加路由环境
√ Add Vue Router for Single Page Application development?
## 是否添加pinia环境
√ Add Pinia for state management?
## 是否添加单元测试
√ Add Vitest for Unit Testing?
## 是否添加端到端测试方案
√ Add an End-to-End Testing Solution?
## 是否添加ESLint语法检查
√ Add ESLint for code quality?
## 是否添加Prettiert代码格式化
√ Add Prettier for code formatting?

自己动手编写一个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 {
background-color: #ddd;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>

2-vue3项目文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public                    // 静态资源文件夹,构建时文件会原封不动复制到dist根目录
favicon.ico // 网站页签图标文件
src // 项目源代码核心目录,所有业务代码、组件、逻辑均存放于此
assets // 项目静态资源目录,Vite会对其中资源做编译(如图片hash命名)
components // 全局/通用组件目录,存放可复用的Vue组件
router // 路由配置目录,存放Vue Router的路由规则、路由守卫等相关代码
stores // Pinia状态管理目录,存放全局状态的store模块
views // 页面级组件目录,存放对应路由的页面组件
App.vue // 根组件,项目所有页面的父容器,可配置全局布局、路由出口等
main.ts // 项目入口文件,创建Vue实例、挂载根组件、配置全局插件等
.gitignore // Git版本控制忽略文件配置
env.d.ts // TypeScript类型声明文件,解决TS类型提示问题
index.html // 项目入口HTML文件,包含Vue挂载的根节点
package.json // 项目依赖配置文件
README.md // 项目说明文档
tsconfig.app.json // TypeScript针对Vue应用代码的编译配置,仅作用于src目录下的业务代码
tsconfig.json // TypeScript根配置文件,全局通用的TS编译规则
tsconfig.node.json // TypeScript针对Vite/node端代码的编译配置
vite.config.ts // Vite构建工具的配置文件

3-Vue3核心语法

OptionsAPI 与 CompositionAPI

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

Options API 的弊端

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

1.gif2.gif

Composition API 的优势

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

3.gif4.gif

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

setup 的返回值

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

setup 与 Options API 的关系

  • Vue2 的配置(datamethos……)中可以访问到 setup中的属性、方法。
  • 但在setup不能访问到Vue2的配置(datamethos……)。
  • 如果与Vue2冲突,则setup优先。

setup 语法糖

setup函数有一个语法糖,这个语法糖,可以让我们把setup独立出去,代码如下:

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. 第三步:<script setup lang="ts" name="Person">

响应式数据

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>

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

  • 作用:定义一个响应式对象(基本类型不要用它,要用ref,否则报错)
  • 语法:let 响应式对象= reactive(源对象)
  • 返回值:一个Proxy的实例对象,简称:响应式对象。
  • 注意点:reactive定义的响应式数据是“深层次”的。定义的数据是不可以整体修改的,若要修改使用object.assign
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>

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>

ref 对比 reactive

宏观角度看:

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

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

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

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

image-20260212192031291

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

toRefs 与 toRef

  • 作用:将一个响应式对象中的每一个属性,转换为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)

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

// 方法
function changeName(){
name.value += '~'
}
function changeAge(){
age.value += 1
}
function changeGender(){
gender.value = '女'
}
</script>

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
<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
}) */


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

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

watch监视

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

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

情况一

监视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
<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'
// 数据
let sum = ref(0)
// 方法
function changeSum(){
sum.value += 1
}
// 监视,情况一:监视【ref】定义的【基本类型】数据
const stopWatch = watch(sum,(newValue,oldValue)=>{
console.log('sum变化了',newValue,oldValue)
if(newValue >= 10){
stopWatch()
}
})
</script>

情况二

监视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
<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'
// 数据
let person = ref({
name:'张三',
age:18
})
// 方法
function changeName(){
person.value.name += '~'
}
function changeAge(){
person.value.age += 1
}
function changePerson(){
person.value = {name:'李四',age:90}
}
/*
监视,情况一:监视【ref】定义的【对象类型】数据,监视的是对象的地址值,若想监视对象内部属性的变化,需要手动开启深度监视
watch的第一个参数是:被监视的数据
watch的第二个参数是:监视的回调
watch的第三个参数是:配置对象(deep、immediate等等.....)
*/
watch(person,(newValue,oldValue)=>{
console.log('person变化了',newValue,oldValue)
},{deep:true})

</script>

情况三

监视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
<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'
// 数据
let person = reactive({
name:'张三',
age:18
})
let 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】定义的【对象类型】数据,且默认是开启深度监视的
watch(person,(newValue,oldValue)=>{
console.log('person变化了',newValue,oldValue)
})
watch(obj,(newValue,oldValue)=>{
console.log('Obj变化了',newValue,oldValue)
})
</script>

情况四

监视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
<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'

// 数据
let 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,(newValue,oldValue)=>{
console.log('person.name变化了',newValue,oldValue)
}) */

// 监视,情况四:监视响应式对象中的某个属性,且该属性是对象类型的,可以直接写,也能写函数,更推荐写函数
//第一个箭头函数是getter 函数
watch(()=>person.car,(newValue,oldValue)=>{
console.log('person.car变化了',newValue,oldValue)
},{deep: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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<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'

// 数据
let 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>

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
    <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'
    // 数据
    let temp = ref(0)
    let height = ref(0)

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

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

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

标签的 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
<template>
<div class="person">
<h1 ref="title1">尚硅谷</h1>
<h2 ref="title2">前端</h2>
<h3 ref="title3">Vue</h3>
<input type="text" ref="inpt"> <br><br>
<button @click="showLog">点我打印内容</button>
</div>
</template>

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

let title1 = ref()
let title2 = ref()
let title3 = ref()

function showLog(){
// 通过id获取元素
const t1 = document.getElementById('title1')
// 打印内容
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
<!-- 父组件App.vue -->
<template>
<Person ref="ren"/>
<button @click="test">测试</button>
</template>

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

let ren = ref()

function test(){
console.log(ren.value.name)
console.log(ren.value.age)
}
</script>


<!-- 子组件Person.vue中要使用defineExpose暴露内容 -->
<script lang="ts" setup name="Person">
import {ref,defineExpose} from 'vue'
// 数据
let name = ref('张三')
let age = ref(18)
/****************************/
/****************************/
// 使用defineExpose将组件中的数据交给外部
defineExpose({name,age})
</script>

props

1
2
3
4
5
6
7
8
9
// 定义一个接口,限制每个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
<template>
<Person :list="persons" />
</template>

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

let 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
<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, withDefaults } from 'vue';
import { type PersonInter } from '@/types';

// 第三种写法:接收+限制类型+指定默认值+限制必要性
const {personList = 'zhangsan'} = defineProps<{personList:Persons}> // vue3.5废弃withDefaults 使用解构赋值设置默认值

console.log(props);
</script>

生命周期

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

  • 规律:

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

  • Vue2的生命周期

    创建阶段:beforeCreatecreated

    挂载阶段:beforeMountmounted

    更新阶段:beforeUpdateupdated

    销毁阶段:beforeDestroydestroyed

  • Vue3的生命周期

    创建阶段:setup

    挂载阶段:onBeforeMountonMounted

    更新阶段:onBeforeUpdateonUpdated

    卸载阶段:onBeforeUnmountonUnmounted

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

  • 示例代码:

    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>当前求和为:{{ sum }}</h2>
    <button @click="changeSum">点我sum+1</button>
    </div>
    </template>

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

    // 数据
    let 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>

自定义hook

  • 什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装,类似于vue2.x中的mixin将组件中的可复用逻辑提取出来,实现逻辑封装与跨组件共享,同时保持响应式系统的完整性和类型安全。

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

示例代码:

  • 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
    27
    28
    import {reactive,onMounted} from 'vue'
    import axios,{AxiosError} from 'axios'

    export default function(){
    let dogList = reactive<string[]>([])

    // 方法
    async function getDog(){
    try {
    // 发请求
    let {data} = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
    // 维护数据
    dogList.push(data.message)
    } catch (error) {
    // 处理错误
    const err = <AxiosError>error
    console.log(err.message)
    }
    }

    // 挂载钩子
    onMounted(()=>{
    getDog()
    })

    //向外部暴露数据
    return {dogList,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
    <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 useSum from './hooks/useSum'
    import useDog from './hooks/useDog'

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

4-路由

  • 路径 (Path): URL 中的一部分,用来标识特定的资源或视图。
  • 路由 (Route): 路由是一个映射,将路径与应该呈现的组件关联起来。
  • 动态路由匹配: 允许你在路径中使用参数,以便为用户提供个性化的响应。
  • 嵌套路由: 表示一个组件内部可以有多个子视图,每个子视图可以有自己的组件和路径。
  • 导航守卫 (Navigation Guards): 可以在导航到新页面之前、之后执行一些逻辑,例如权限检查或获取数据。

路由

基本切换效果

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

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import {createRouter,createWebHistory} from 'vue-router'
    import Home from '@/pages/Home.vue'
    import News from '@/pages/News.vue'
    import About from '@/pages/About.vue'

    const router = createRouter({
    history:createWebHistory(),
    routes:[
    {
    path:'/home',
    component:Home
    },
    {
    path:'/about',
    component:About
    }
    ]
    })
    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>
  1. 路由组件通常存放在pagesviews文件夹,一般组件通常存放在components文件夹。

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

路由器工作模式

  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模式
    /******/
    })

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>

命名路由

作用:可以简化路由跳转及传参。

给路由规则命名:

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>

嵌套路由

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

  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
    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. 跳转路由(要加完整路径):

    1
    2
    3
    <router-link to="/news/detail">xxxx</router-link>
    <!-- 或 -->
    <router-link :to="{path:'/news/detail'}">xxxx</router-link>
  4. 记得去Home组件中预留一个<router-view>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <template>
    <div class="news">
    <nav class="news-list">
    <RouterLink v-for="news in newsList" :key="news.id" :to="{path:'/news/detail'}">
    {{news.name}}
    </RouterLink>
    </nav>
    <div class="news-detail">
    <RouterView/>
    </div>
    </div>
    </template>

路由传参

query参数

  1. 传递参数News.vue

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <!-- 跳转并携带query参数(to的字符串写法) -->
    <router-link to="/news/detail?a=1&b=2&content=欢迎你">
    跳转
    </router-link>

    <!-- 跳转并携带query参数(to的对象写法) -->
    <RouterLink
    :to="{
    //name:'xiang', //用name也可以跳转
    path:'/news/detail',
    query:{
    id:news.id,
    title:news.title,
    content:news.content
    }
    }"
    >
    {{news.title}}
    </RouterLink>
  2. 接收参数Detail.vue

    1
    2
    3
    4
    import {useRoute} from 'vue-router'
    const route = useRoute()
    // 打印query参数
    console.log(route.query)

params参数

  1. 参数占位index.ts
1
2
3
4
5
6
7
8
9
10
11
12
{
name: "news",
path: "/news",
component: News,
children: [
{
name: "detail",
path: "detail/:id/:title/:content",
component: Detail,
},
],
},
  1. 传递参数News.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 跳转并携带params参数(to的字符串写法) -->
<RouterLink :to="`/news/detail/001/新闻001/内容001`">{{news.title}}</RouterLink>

<!-- 跳转并携带params参数(to的对象写法) -->
<RouterLink
:to="{
name:'xiang', //用name跳转
params:{
id:news.id,
title:news.title,
content:news.title
}
}"
>
{{news.title}}
</RouterLink>
  1. 接收参数Detail.vue
1
2
3
4
import {useRoute} from 'vue-router'
const route = useRoute()
// 打印params参数
console.log(route.params)

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

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

路由的props配置

作用:让路由组件更方便的收到参数(可以将路由参数作为props传给组件),相当于<Detail/id:xx/title:xx/content:xx>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
name:'xiang',
path:'detail/:id/:title/:content',
component:Detail,

// props的对象写法,作用:把对象中的每一组key-value作为props传给Detail组件
// props:{a:1,b:2,c:3},

// props的布尔值写法,作用:把收到了每一组params参数,作为props传给Detail组件
// props:true

// props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件
props(route){
return route.query
}
}

replace属性

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

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

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

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

编程式导航

路由组件的两个重要的属性:$route$router变成了两个hooks,RouterLink不能在脚本里使用

1
2
3
4
5
6
7
8
9
10
11
12
<h3 @click=clickToHome>点击跳转</h3>

<script>//脚本
// 等候三秒跳转
function clickToHome() {
setTimeout(() => {
router.push({
name: 'home'
})
}, 3000)
}
<script/>

重定向

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

  2. 具体编码:

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

5-pinia

搭建 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选项

存储+读取数据

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

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

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

    将几个组件公共的数据存放在此

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

    // 定义并暴露一个store
    export const useCountStore = defineStore('count',{
    // 动作
    actions:{},
    // 状态
    state(){
    return {
    sum:6
    }
    },
    // 计算
    getters:{}
    })
  4. 具体编码:src/store/talk.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 useTalkStore = defineStore('talk',{
    // 动作
    actions:{},
    // 状态
    state(){
    return {
    talkList:[
    {id:'yuysada01',content:'你今天有点怪,哪里怪?怪好看的!'},
    {id:'yuysada02',content:'草莓、蓝莓、蔓越莓,你想我了没?'},
    {id:'yuysada03',content:'心里给你留了一块地,我的死心塌地'}
    ]
    }
    },
    // 计算
    getters:{}
    })
  5. 组件中使用state中的数据

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

    <script setup lang="ts" name="Count">
    // 引入对应的useXxxxxStore
    import {useSumStore} from '@/store/sum'

    // 调用useXxxxxStore得到对应的store
    const sumStore = useSumStore()
    </script>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <template>
    <ul>
    <li v-for="talk in talkStore.talkList" :key="talk.id">
    {{ talk.content }}
    </li>
    </ul>
    </template>

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

    const talkStore = useTalkStore()
    </script>

修改数据(三种方式)

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

    1
    countStore.sum = 666
  2. 第二种修改方式:批量修改

    1
    2
    3
    4
    countStore.$patch({
    sum:999,
    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
    21
    import { defineStore } from 'pinia'

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

    组件中调用action即可

    1
    2
    3
    4
    5
    // 使用countStore
    const countStore = useCountStore()

    // 调用对应action
    countStore.incrementOdd(n.value)

storeToRefs

  • 借助storeToRefsstore中的数据转为ref对象,方便在模板中使用。
  • 注意:pinia提供的storeToRefs只会将数据做转换,而VuetoRefs会转换store中数据。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<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,随后解构 */
const {sum} = storeToRefs(countStore)
</script>

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
    // 引入defineStore用于创建store
    import {defineStore} from 'pinia'

    // 定义并暴露一个store
    export const useCountStore = defineStore('count',{
    // 动作
    actions:{
    /************/
    },
    // 状态
    state(){
    return {
    sum:1,
    school:'atguigu'
    }
    },
    // 计算
    getters:{
    bigSum:(state):number => state.sum *10,
    upperSchool():string{
    return this. school.toUpperCase()
    }
    }
    })
  3. 组件中读取数据:

    1
    2
    const {increment,decrement} = countStore
    let {sum,school,bigSum,upperSchool} = storeToRefs(countStore)

$subscribe

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

1
2
3
4
5
//mutate:修改的信息,stat:存储的数据
talkStore.$subscribe((mutate,state)=>{
console.log('LoveTalk',mutate,state)
localStorage.setItem('talk',JSON.stringify(talkList.value))
})

store组合式写法

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

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

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

6-组件通信

props

概述:props是使用频率最高的一种通信方式,props通常是父组件向子组件传递数据的方式,而子组件向父组件传递数据一般是通过事件。

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

父组件:

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>我的车:{{ car }}</h4>
<h4>儿子给的玩具:{{ toy }}</h4>
<Child :car="car" :getToy="getToy"/>
</div>
</template>

<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
// 数据
const car = ref('奔驰')
const toy = ref()
// 方法
function getToy(value:string){
toy.value = value
}
</script>

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<div class="child">
<h3>子组件</h3>
<h4>我的玩具:{{ toy }}</h4>
<h4>父给我的车:{{ car }}</h4>
<button @click="getToy(toy)">玩具给父亲</button>
</div>
</template>

<script setup lang="ts" name="Child">
import { ref } from "vue";
const toy = ref('奥特曼')

defineProps(['car','getToy'])
</script>

自定义事件

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

    Child.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>
    <h1>这里是子组件</h1>
    <button @click="sendtToyButton">发送玩具</button>
    </template>

    <script setup lang="ts" name="Child">

    // 声明可触发的事件列表(可携带参数)
    const emit = defineEmits(['send-toy'])

    //子组件的数据
    let toy = '奥特曼'

    //自定义事件
    const sendtToyButton = () => {
    // 触发事件,发送子组件数据
    emit('send-toy', toy)
    }

    </script>

    <style scoped>

    </style>

    Father.vue

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <template>
    <!-- 监听到子组件出触发事件调用函数接受数据 -->
    <Child @send-toy="reciveData" />
    <p>收到子组件的值:{{ recive }}</p>
    </template>

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

    const recive = ref('')
    const reciveData = (data: any) => {
    recive.value = data
    }


    </script>

    <style scoped>

    </style>

HTML属性是不区分大小写的,所以使用短横线命名法可以避免一些问题

mitt

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

安装mitt

1
npm i 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
// 引入mitt 
import mitt from "mitt";

// 创建emitter
const emitter = mitt()

/*
// 绑定事件
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.all.clear()
}, 3000);
*/

// 创建并暴露mitt
export default emitter

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

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

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

v-model

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

  2. 前序知识 —— v-model的本质

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

    <!-- v-model的本质是下面这行代码 -->
    <input
    type="text"
    :value="userName"
    @input="userName =(<HTMLInputElement>$event.target).value"
    >
  3. 组件标签上的v-model的本质::moldeValueupdate:modelValue事件。

    1
    2
    3
    4
    5
    <!-- 组件标签上使用v-model指令 -->
    <AtguiguInput v-model="userName"/>

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

    AtguiguInput组件中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <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>
  4. 也可以更换value,例如改成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
    <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>
  5. 如果value可以更换,那么就可以在组件标签上多次使用v-model

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

$attrs

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

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

    注意:$attrs会自动排除props中声明的属性(可以认为声明过的 props 被子组件自己“消费”了)

父组件:

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

<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
let a = ref(1)
let b = ref(2)
let c = ref(3)
let d = ref(4)

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

子组件:

1
2
3
4
5
6
7
8
9
10
<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
<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>

$refs、$parent

  1. 概述:

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

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

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
    <template>
    <div class="father">
    <h3>父组件</h3>
    <h4>资产:{{ money }}</h4>
    <h4>汽车:{{ car }}</h4>
    <button @click="money += 1">资产+1</button>
    <button @click="car.price += 1">汽车价格+1</button>
    <Child/>
    </div>
    </template>

    <script setup lang="ts" name="Father">
    import Child from './Child.vue'
    import { ref,reactive,provide } from "vue";
    // 数据
    let money = ref(100)
    let car = reactive({
    brand:'奔驰',
    price:100
    })
    // 用于更新money的方法
    function updateMoney(value:number){
    money.value += value
    }
    // 提供数据
    provide('moneyContext',{money,updateMoney})
    provide('car',car)
    </script>

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

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <template>
    <div class="grand-child">
    <h3>我是孙组件</h3>
    <h4>资产:{{ money }}</h4>
    <h4>汽车:{{ car }}</h4>
    <button @click="updateMoney(6)">点我</button>
    </div>
    </template>

    <script setup lang="ts" name="GrandChild">
    import { inject } from 'vue';
    // 注入数据
    let {money,updateMoney} = inject('moneyContext',{money:0,updateMoney:(x:number)=>{}})
    let car = inject('car')
    </script>

pinia

详见上文

slot

默认插槽

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>

具名插槽

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
父组件中:
<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>

作用域插槽

  1. 理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(新闻数据在News组件中,但使用数据所遍历出来的结构由App组件决定)

  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
    父组件中:
    <Game v-slot="params">
    <!-- <Game v-slot:default="params"> -->
    <!-- <Game #default="params"> -->
    <ul>
    <li v-for="g in params.games" :key="g.id">{{ g.name }}</li>
    </ul>
    </Game>

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

总结

image-20260226202158835