在Vue3中,ref 和 reactive 是两种用于创建响应式数据的核心API。我们可以通过使用 watch 函数来观察这些响应式数据的变化。watch 是Vue3中 提供的一个API,用于响应式地追踪一个或多个源,并在源发生变化时运行一个回调函数。
如何观察 ref 对象
假设我们有一个 ref 对象,我们可以这样设置观察者:
javascriptimport { ref, watch } from 'vue'; export default { setup() { const count = ref(0); watch(count, (newValue, oldValue) => { console.log(`count的值从 ${oldValue} 变更为 ${newValue}`); }); return { count }; } }
在上面的例子中,count 是一个使用 ref 创建的响应式引用。使用 watch 函数观察 count 的变化,每当 count 的值发生变化时,都会调用我们提供的回调函数,并打印新旧值。
如何观察 reactive 对象
对于 reactive 对象,观察的方式与 ref 类似,但是通常我们会观察 reactive 对象的某个特定属性:
javascriptimport { reactive, watch } from 'vue'; export default { setup() { const state = reactive({ count: 0 }); watch(() => state.count, (newValue, oldValue) => { console.log(`count的值从 ${oldValue} 变更为 ${newValue}`); }); return { state }; } }
在这个例子中,state 是一个使用 reactive 创建的响应式对象。此处我们使用了 watch 的一个变种,它接受一个函数作为第一个参数,该函数返回我们想要观察的响应式属性(state.count)。每当 count 值变化时,就会触发回调函数。
一个更复杂的例子
如果我们想同时观察 ref 和 reactive 对象,我们可以将它们组合在一个 watch 中:
javascriptimport { ref, reactive, watch } from 'vue'; export default { setup() { const count = ref(0); const state = reactive({ text: 'hello' }); watch([count, () => state.text], ([newCount, newText], [oldCount, oldText]) => { console.log(`count的值从 ${oldCount} 变更为 ${newCount}`); console.log(`text的值从 ${oldText} 变更为 ${newText}`); }); return { count, state }; } }
在这个例子中,我们同时观察了 count 和 state.text。通过将它们放在一个数组中,并在 watch 函数中使用,我们可以在一个回调中同时处理它们的变化,这在需要观察多个源并对变化做集中处理的场景非常有用。
总结
使用 Vue3 的 watch API 为 ref 和 reactive 对象设置观察者是非常直接和灵活的,可以帮助我们在数据变化时执行特定的逻辑,对于构建响应式的用户界面非常有帮助。
2024年11月21日 09:13 回复