vue2

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>
<h2>{{ message }}</h2>
<button @click="info.name = 'kkk'">修改message</button>
<button @click="info.friends.name = 'oooo'">修改message</button>
</template>

<script>
export default {
data() {
return {
info: {
name: "ddd",
friends: { name: "ppp" },
},
};
},
watch: {
info: {
handler: (newValue, oldvalue) => {
console.log(newValue, oldvalue);
},
immediate: true,
deep: true,
},
},
};
</script>

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
40
41
42
43
44
<template>
<h2>{{ message }}</h2>
<button @click="message = 'ooo'">修改message</button>
<button @click="info.name = 'ooo'">修改message</button>
<button @click="info.friends.name = 'james'">修改message</button>
</template>

<script setup>
import { ref, watch, reactive } from "vue";
const message = ref("hello");
const info = reactive({
name: "hh",
friends: { name: "jack" },
});
watch(message, (newValue, oldValue) => {
console.log(newValue, oldValue);
});


/**
* 响应式对象 默认进行了深度监听
* 并且newValue oldValue指向同一内存地址
* 所以newValue里的info.name改变了,打印出来的oldValue里的info.name也会改变
*/
//Proxy {name: 'ooo', friends: {…}}[[Handler]]: Object[[Target]]: Object[[IsRevoked]]: false Proxy {name: 'ooo', friends: {…}}
watch(info, (newValue, oldValue) => {
console.log(newValue, oldValue);
});



/**
* 这种情况的info不是响应式对象,深度监听要配置deep
* 且返回的不再是proxy代理对象
*/
watch(
() => ({ ...info }),
(newValue, oldValue) => {
console.log(newValue, oldValue);
},
{ deep: true, immediate: true }
);
</script>

watchEffect

watchEffect 会自动收集依赖,依赖改变,就会执行函数

1
2
3
4
5
const counter = ref(0);
watchEffect(() => {
console.log(counter.value);
});
</script>

停止监听

1
2
3
4
5
6
7
8
const counter = ref(0);
const stopWatch = watchEffect(() => {
console.log(counter.value);

if (counter.value > 5) {
stopWatch();
}
});