watch 需要侦听特定的数据源,并在单独的回调函数中执行副作用

  • watch第一个参数监听源,监听多个ref 注意变成数组啦
  • watch第二个参数回调函数cb(newVal,oldVal)
  • watch第三个参数一个options配置项是一个对象
    1. {
    2. immediate: true //是否立即调用一次
    3. deep: true //是否开启深度监听
    4. }

immediate: true 是否立即调用一次

  1. <script setup lang="ts">
  2. import { watch, ref } from "vue";
  3. let msg = ref("小雪");
  4. let msg1 = ref("小满");
  5. watch(
  6. [msg, msg1],
  7. (newVale, oldVal) => {
  8. console.log("新", newVale);
  9. console.log("旧", oldVal);
  10. },
  11. {
  12. immediate: true,
  13. }
  14. );
  15. </script>
  16. <template>
  17. <input type="text" v-model="msg" />
  18. <input type="text" v-model="msg1" />
  19. </template>

image.png

deep:true是否开启深度监听

  1. <script setup lang="ts">
  2. import { watch, ref } from "vue";
  3. let msg = ref({
  4. nav:{
  5. bar:{
  6. name:"小雪"
  7. }
  8. }
  9. });
  10. watch(
  11. msg,
  12. (newVale, oldVal) => {
  13. console.log("新", newVale);
  14. console.log("旧", oldVal);
  15. }
  16. );
  17. </script>
  18. <template>
  19. <input type="text" v-model="msg.nav.bar.name" />
  20. </template>
  21. <style></style>

没有任何打印结果,加了deep:true以后:
image.png
这是Vue的一个Bug,新值旧值一样

监听Reactive

使用reactive监听深层对象开启和不开启deep 效果一样

  1. <script setup lang="ts">
  2. import { watch, ref,reactive } from "vue";
  3. let msg = reactive({
  4. nav:{
  5. bar:{
  6. name:"小雪"
  7. }
  8. }
  9. });
  10. watch(
  11. msg,
  12. (newVale, oldVal) => {
  13. console.log("新", newVale);
  14. console.log("旧", oldVal);
  15. }
  16. );
  17. </script>
  18. <template>
  19. <input type="text" v-model="msg.nav.bar.name" />
  20. </template>

监听reactive 单一值

  1. <script setup lang="ts">
  2. import { watch, ref, reactive } from "vue";
  3. let msg = reactive({
  4. name1: "小雪",
  5. name2: "小兰",
  6. });
  7. watch(
  8. () => msg.name1,
  9. (newVale, oldVal) => {
  10. console.log("新", newVale);
  11. console.log("旧", oldVal);
  12. }
  13. );
  14. </script>
  15. <template>
  16. <input type="text" v-model="msg.name1" />
  17. <input type="text" v-model="msg.name2" />
  18. </template>

image.png
用reactive可以不写deep也能监听到
image.png

image.png