watch介绍

vue中watch用来监听数据的响应式变化.获取数据变化前后的值
watch的完整入参

watch(监听的数据,副作用函数,配置对象)
watch(data, (newData, oldData) => {}, {immediate: true, deep: true})

watch监听的不同情况

创建响应式数据

import { ref, watch, reactive } from "vue";
let name = ref("moxun");
let age = ref(18);
let person = reactive({
  Hobby: "photo",
  city: {
    jiangsu: {
      nanjing: "雨花台",
    },
  },
});

1 监听单个refimpl数据

watch(name, (newName, oldName) => {
  console.log("newName", newName);
});

2 监听多个refimpl数据

方式一:vue3允许多个watch监听器存在

watch(name, (newValue, oldValue) => {
  console.log("new", newValue, "old", oldValue);
});
watch(age, (newValue, oldValue) => {
  console.log("new", newValue, "old", oldValue);
});

方式二:将需要监听的数据添加到数组

watch([name, age], (newValue, oldValue) => {
  // 返回的数据是数组
  console.log("new", newValue, "old", oldValue);
});

3 监听proxy数据

注意

1.此时vue3将强制开启deep深度监听
2.当监听值为proxy对象时,oldValue值将出现异常,此时与newValue相同

// 监听proxy对象
watch(person, (newValue, oldValue) => {
  console.log("newValue", newValue, "oldValue", oldValue);
});

4 监听proxy数据的某个属性

需要将监听值写成函数返回形式,vue3无法直接监听对象的某个属性变化

watch(
  () => person.Hobby,
  (newValue, oldValue) => {
    console.log("newValue",newValue, "oldvalue", oldValue);
  }
);

注意
当监听proxy对象的属性为复杂数据类型时,需要开启deep深度监听

watch(
  () => person.city,
  (newvalue, oldvalue) => {
    console.log("person.city newvalue", newvalue, "oldvalue", oldvalue);
  },{
    deep: true
  }
);

5 监听proxy数据的某些属性

watch([() => person.age, () => person.name], (newValue, oldValue) => {
  // 此时newValue为数组
  console.log("person.age", newValue, oldValue);
});

总结

1.与vue2中的watch配置一致
2.两个坑:

监听reactive定义的proxy代理数据时
oldValue无法正确获取
强制开启deep深度监听(无法关闭)

监听reactive定义的proxy代理对象某个属性时deep配置项生效

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐