watch 侦听器
# watch
用于侦听响应式数据的变化,比如使用ref,reactive声明的变量
源码错误提醒定义
const warnInvalidSource = (s) => {
warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
`a reactive object, or an array of these types.`);
};
1
2
3
4
2
3
4
- 用法
watch(source, cb, options)
source:ref / reactive / [ ref、reactive ] / gettter
cb: 回调函数;
option: {
deep: true, // 开启深度监听
immediate: true, // 是否立即执行,默认为false
flush: "pre", //默认为pre; pre:组件更新之前调用 async: 同步执行; post: 组件更新之后调用
}
<template>
<div class="wrapper">
<div>
first: <input v-model="refName" />
</div>
<div>
last: <input v-model="reactiveName.name" />
</div>
<div>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref, watch, reactive } from "vue"
let reactiveName = reactive({
name: ""
})
let refName = ref("")
watch(refName, (newVal, oldVal)=>{
console.log("change", newVal, oldVal)
})
watch(reactiveName, (newVal, oldVal)=>{
console.log("change", newVal, oldVal)
}, {
deep: true, // 如果侦听的是reactive类型数据,则内部自动开启deep
immediate: true,
flush: "pre"
})
</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
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
- 源码流程
// step 1: 格式化参数
因为watch可以接收多种类型的参数,那么就要格式化参数: 格式化参数结果就是赋值getter函数
// step 2: 判断执行方式 pre or async or post, 并将对应的处理函数赋值给调度函数
// step 3: 执行计算
1
2
3
4
5
2
3
4
5
编辑 (opens new window)
上次更新: 2023/05/17, 21:35:56