vue3-watch和watchEffect区别

7/18/2020 vue3
  • 两者都可以监听data属性变化
  • watch需要明确监听哪个属性
  • watchEffect会根据其中的属性,自动监听其变化

# watch

watch需要明确监听哪个属性

<template>
    <div>
        {{ numberRef }}--{{ name }} {{ age }}
    </div>
</template>


<script lang="ts">
import { ref, reactive, toRefs, watch, watchEffect } from 'vue';
export default {
    name: 'Watch',
    setup() {
        const numberRef = ref<number>(100)

        const state = reactive({
            name: 'zhangsan',
            age: 20
        })

        watch(numberRef, (newVal, oldVal) => {
            console.log('numberRef watch', newVal, oldVal);
        }, {
            immediate: true
        })

        /**
         * 第一个参数: 确定要监听哪个属性
         * 第二个参数: 回调函数
         * 第三个参数: 配置项  初始化之前就监听; 深度监听  (可选)
         */
        watch(() => state.age, (newVal, oldVal) => {
            console.log('state age watch', newVal, oldVal);
        },{
            immediate: true
        })

        watch(() => state.name, (newVal, oldVal) => {
            console.log('state name watch', newVal, oldVal);
        },{
            immediate: true
        })

        setTimeout(() => {
            numberRef.value = 200
        }, 1500)

        setTimeout(() => {
            state.name = 'lisi'
        }, 3500)

        setTimeout(() => {
            state.age = 30
        }, 4500)

        return {
            numberRef,
            ...toRefs(state)
        }
    }
}
</script>

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

# watchEffect

watchEffect会根据其中的属性,自动监听其变化

<template>
    <div>
        {{ numberRef }}--{{ name }} {{ age }}
    </div>
</template>
<script lang="ts">
import { ref, reactive, toRefs, watch, watchEffect } from 'vue';
export default {
    name: 'Watch',
    setup() {
        const numberRef = ref<number>(100)

        const state = reactive({
            name: 'zhangsan',
            age: 20
        })


        watchEffect(() => {
            console.log('初始化时,一定执行一次,收集要监听的数据');
        })


        watchEffect(() => {
            console.log('state.name', state.name);
        })

        watchEffect(() => {
            console.log('state.age', state.age);
        })

        setTimeout(() => {
            state.name = 'lisi'
        }, 2000)

        setTimeout(() => {
            state.age = 30
        }, 4500)

        return {
            numberRef,
            ...toRefs(state)
        }
    }
}
</script>
<style>
</style>
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
更新: 7/25/2022, 3:15:19 PM