vue3-watch

7/18/2020 vue3

需要侦听特定的数据源,并在单独的回调函数中执行副作用。默认情况下,它也是惰性的——即回调仅在侦听源发生变化时被调用。

# 入参


watch(
  "数据源",
  回调函数(newVal,oldVal) => {},
  { // 配置项
    immediate:true, //是否立即调用一次
    deep:true //是否开启深度监听
  }
)
1
2
3
4
5
6
7
8

# 监听ref


监听单一ref

<template>
  <div>
    <div>{{count}}</div>
    <button @click="handleClick">更新</button>

  </div>
</template>
 
<script setup lang="ts">
import { ref, watch } from 'vue';

let count = ref<number>(0)

watch(count, (newVal,oldVal) => {
  console.log('newVal', newVal);
  console.log('oldVal', oldVal);
})

const handleClick = () => {
  count.value ++
}

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

监听单一ref 第一个参数成数组

<template>
  <div>
    <div>{{ count }} {{ message }}</div>
    <button @click="handleClick">更新</button>

  </div>
</template>
 
<script setup lang="ts">
import { ref, watch } from 'vue';

let count = ref<number>(0)

let message = ref<string>("")

watch([count, message], (newVal, oldVal) => {
  console.log('newVal', newVal);
  console.log('oldVal', oldVal);
})

const handleClick = () => {
  count.value++
  message.value += count.value + '-'
}

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

# 监听reactive


单一对象源 reactive监听,第一个参数 是getter()函数

<template>
  <div>
    <div>{{ newObj }}</div>
    <button @click="handleClick">更新</button>

  </div>
</template>
 
<script setup lang="ts">
import { reactive, watch } from 'vue';

let obj = {
  a: 1,
  b: 2,
}

let newObj = reactive(obj)

watch(() => newObj.a, (newVal, oldVal) => {
  console.log('newVal', newVal);
  console.log('oldVal', oldVal);
}, {
  immediate: true, //是否立即调用一次
  deep: true //是否开启深度监听
})

const handleClick = () => {
  newObj.a ++
  console.log(newObj);
}

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

多级对象

<template>
  <div>
    <div>{{ newObj }}</div>
    <button @click="handleClick">更新</button>
  </div>
</template>
 
<script setup lang="ts">
import { reactive, watch } from 'vue';

let obj = {
  a: 1,
  b: 2,
  c: {
    d: 3
  }
}

let newObj = reactive(obj)

watch(newObj, (newVal, oldVal) => {
  console.log('newVal', newVal);
  console.log('oldVal', oldVal);
})

const handleClick = () => {
  newObj.a = 11
  newObj.c.d = 33
}

</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
更新: 7/25/2022, 3:15:19 PM