vue3中watch与watchEffect使用与区别

const count: Ref = ref(0);
//只监听一个参数时
watch(count, (n, o) => {
  console.log(n, o);
});

//两种监听方式--watchEffect
watchEffect(() => {
  //写入了依赖项,如果依赖性有变化就会监听到
  console.log(count.value);
});

vue3中watch与watchEffect使用与区别_第1张图片

//级联选择器绑定值
const csaData = reactive({
  data: [
    ["guide", "disciplines", "feedback"],
    ["guide", "disciplines", "controllability"],
  ],
});

//监听整个reactive对象:
watch(csaData, (n, o) => {
  console.log('watch1:',n.data, o.data);
});

//监听某个属性:
watch(
  () => csaData.data,
  (n, o) => {
    console.log("watch2:", n, o);
  }
);

watchEffect(() => {
  console.log("watchEffect:", csaData.data);
});

 vue3中watch与watchEffect使用与区别_第2张图片

 

//级联选择器绑定值
const csaData = reactive({
  data: [
    ["guide", "disciplines", "feedback"],
    ["guide", "disciplines", "controllability"],
  ],
});


const count: Ref = ref(0);
setInterval(() => count.value++, 2000);

//watch可以以数组方式
watch([count, () => csaData.data], (n, o) => {
  console.log("watch:", n, o);
});

//只要有一个依赖改变就会触发
watchEffect(() => {
  console.log("watchEffect:", count.value);
  console.log("watchEffect:", csaData.data);
});

你可能感兴趣的:(vue3,vue.js,javascript,elementui)