在Vue 3中,可以使用watch函数来监听数据的变化。watch函数的基本语法如下:

watch(source, callback, options)

其中,source可以是一个响应式的数据,也可以是一个返回响应式数据的函数。callback是一个回调函数,用于处理数据变化时的逻辑。options是一个可选参数对象,用于配置watch的行为。

下面是一些watch的使用示例:

  1. 监听一个响应式数据的变化:
const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`);
});
  1. 监听一个返回响应式数据的函数的变化:
const count = ref(0);

const getCount = () => {
  return count.value;
};

watch(getCount, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`);
});
  1. 使用immediate选项来立即执行回调函数:
const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`);
}, { immediate: true });
  1. 使用deep选项来深度监听对象或数组的变化:
const obj = reactive({ name: 'John', age: 30 });

watch(obj, (newValue, oldValue) => {
  console.log('obj changed');
}, { deep: true });
  1. 使用watchEffect函数来监听一个响应式数据的变化,并自动执行回调函数:
const count = ref(0);

watchEffect(() => {
  console.log(`count changed to ${count.value}`);
});

这些示例展示了在Vue 3中使用watch的一些常见用法,你可以根据自己的需求选择适合的方式来监听数据的变化

vue3中watch的使用方法

原文地址: https://www.cveoy.top/t/topic/h8uD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录