Vue 3 中的 watch 函数:实战指南

Vue.js 是一个功能丰富的前端框架,它允许开发者以声明式的方式创建动态和反应式的用户界面。Vue 3 引入的 Composition API 增强了代码的组织和复用,其中 watch 函数是一个非常有用的特性。本文将通过一系列的示例,展示如何在 Vue 3 应用程序中使用 watch 函数来监控数据变化。

监控响应式引用(ref

响应式引用是 Vue 3 中最基本的响应式特性之一。下面的例子演示了如何监控一个响应式引用的变化:

import { ref, watch } from 'vue';

export default {
  setup() {
    const count = ref(0);

    watch(count, (newCount, oldCount) => {
      console.log(`Count changed from ${oldCount} to ${newCount}`);
      if (newCount === 10) {
        alert('Count reached 10!');
      }
    });

    return { count };
  }
};

在这个例子中,每当 count 的值变化时,watch 回调就会执行,并打印出新旧值。

监控响应式对象(reactive

reactive 提供了一个更复杂的响应式状态管理。下面的例子展示了如何监控一个响应式对象的属性变化:

import { reactive, watch } from 'vue';

export default {
  setup() {
    const state = reactive({
      firstName: 'John',
      lastName: 'Doe'
    });

    watch(() => state.firstName, (newFirstName, oldFirstName) => {
      console.log(`First name changed from ${oldFirstName} to ${newFirstName}`);
    });

    watch(() => state.lastName, (newLastName, oldLastName) => {
      console.log(`Last name changed from ${oldLastName} to ${newLastName}`);
    });

    return { state };
  }
};

这个例子中,我们分别监控了 firstNamelastName 属性的变化,并在它们变化时执行回调。

监控计算属性(computed

计算属性是基于它们的响应式依赖进行缓存的。下面的例子展示了如何监控一个计算属性的变化:

import { ref, computed, watch } from 'vue';

export default {
  setup() {
    const firstName = ref('John');
    const lastName = ref('Doe');

    const fullName = computed(() => `${firstName.value} ${lastName.value}`);

    watch(fullName, (newFullName, oldFullName) => {
      console.log(`Full name changed from ${oldFullName} to ${newFullName}`);
    });

    return { firstName, lastName, fullName };
  }
};

在这个例子中,fullName 是一个计算属性,它的值是基于 firstNamelastName 的。当这些依赖变化时,fullName 也会更新,触发 watch 回调。

监控多个数据源

Vue 3 的 watch 也可以同时监控多个数据源。下面的例子展示了如何同时监控多个响应式引用:

import { ref, watch } from 'vue';

export default {
  setup() {
    const width = ref(window.innerWidth);
    const height = ref(window.innerHeight);

    watch([width, height], ([newWidth, newHeight], [oldWidth, oldHeight]) => {
      console.log(`Window size changed from ${oldWidth}x${oldHeight} to ${newWidth}x${newHeight}`);
    });

    return { width, height };
  }
};

这个例子中,我们监控了窗口的 widthheight,并在它们变化时打印出新旧尺寸。

使用 watchimmediatedeep 选项

watch 函数还接受一个配置对象,其中 immediatedeep 选项允许你更精细地控制监控行为:

import { ref, watch } from 'vue';

export default {
  setup() {
    const userProfile = ref({
      name: 'Alice',
      preferences: {
        theme: 'light'
      }
    });

    // 使用 `deep` 选项来深度监控对象内部的变化
    watch(userProfile, (newProfile, oldProfile) => {
      console.log('User profile changed!');
    }, { deep: true });

    // 使用 `immediate` 选项立即触发回调
    watch(userProfile, (newProfile, oldProfile) => {
      console.log('This runs immediately and whenever userProfile changes!');
    }, { immediate: true });

    return { userProfile };
  }
};

在这个例子中,deep 选项允许我们监控 userProfile 对象内部的变化,而 immediate 选项确保了在监控设置之后立即触发一次回调。

结论

Vue 3 的 watch 函数提供了一个强大的接口来响应数据的变化。通过上面的例子,我们看到了如何在不同场景下使用 watch 来监控响应式引用、响应式对象、计算属性以及多个数据源。记住,要谨慎使用 watch,避免不必要的性能开销,并合理利用 immediatedeep 选项来满足特定的需求。

希望这篇文章能够帮助你更好地理解和利用 Vue 3 中的 watch 函数,为你的应用带来更多的动态和响应式特性。祝你在 Vue 3 的世界里编程愉快!

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值